General search in DataGrid or in ObservableCollection

BitSmithy 2,206 Reputation points
2021-09-20T15:06:20.573+00:00

Hello,

I am traing to make a search function which finds in UWP DataGrid or in attached ObservableCollection, any string. Search should be made by specified property.
This work I must to do using general programming .

I started with such code but I stuck.

        public class MyObservableCollection<T> : ObservableCollection<T>
        {
            public int Find(string propertyName, string textToFind)
                    {
                int index;

                //body here

                return index;
            }
            }

please help.

Developer technologies | Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Nico Zhu (Shanghai Wicresoft Co,.Ltd.) 12,866 Reputation points
    2021-09-21T05:58:55.907+00:00

    Hello, Welcome to Micorosoft Q&A,

    Search should be made by specified property.

    For your scenario, I have completed code, please refer the following to filter your collection.

    public class MyObservableCollection<T> : ObservableCollection<T>  
    {  
        public int Find(string propertyName, string textToFind)  
        {  
            int index = -1;  
      
            var FilteredItems = this.Where(item => GetPropertyValue(item, propertyName).ToString().IndexOf(textToFind, StringComparison.InvariantCultureIgnoreCase) >= 0);  
      
            foreach (var item in FilteredItems)  
            {  
                index = this.IndexOf(item);  
            }  
            // we suggest your return FilteredItems, or it will reture last one's index of current collection from FilteredItems  
            return index;  
        }  
      
        object GetPropertyValue(T entity, string propetyName)  
        {  
            object result = null;  
            Type entityType = typeof(T);  
            try  
            {  
                PropertyInfo proInfo = entityType.GetProperty(propetyName);  
                result = proInfo.GetValue(entity);  
            }  
            catch (Exception)  
            {  
      
                throw;  
            }  
            return result;  
        }  
      
    }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.