question

BitSmithy-4663 avatar image
0 Votes"
BitSmithy-4663 asked NicoZhu-MSFT edited

General search in DataGrid or in ObservableCollection

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.


windows-uwp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

NicoZhu-MSFT avatar image
0 Votes"
NicoZhu-MSFT answered NicoZhu-MSFT edited

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.








5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.