Answered by:
Creating Generic Search Method

Question
-
Hi There,
It is possible to create a generic search method where key is unknown; for e.g Key for the List<T> will be passed to the parameter and it performs a like search and return the filtered List<T>.
Code should be something like:
public List<T> LikeSearch<T>(List<T> AllData,T key, string searchString) { List<T> _list = new List<T>(); //Perform the search on AllData based on searchString passed on the key given return _list; }
Uses will be like:
Example 1
List<Users> _users = LikeSearch<Users>(AllUsers,'Name','sam');
Where AllUsers is the list of 100 users.
Example 2
List<Customers> _cust = LikeSearch<Customers>(AllCustomers,'City','London');
Where AllCustomers is the list of 100 Customers.
Please sugest
- Edited by AbhinawK Wednesday, August 24, 2016 9:59 AM
Wednesday, August 24, 2016 9:57 AM
Answers
-
Thank you folks.
I solved my problem. Here is the same code.
public static List<T> LikeSearch<T>(this List<T> data, string key, string searchString) { var property = typeof(T).GetProperty(key); if (property == null) throw new ArgumentException("'{typeof(T).Name}' does not implement a public get property named '{key}'."); return data.Where(d => ((string)property.GetValue(d)).Contains(searchString)).ToList(); }
Hope this will help you people.
- Proposed as answer by Wendy ZangMicrosoft contingent staff Thursday, August 25, 2016 1:32 AM
- Marked as answer by Kevin Linq Wednesday, September 7, 2016 2:17 AM
Wednesday, August 24, 2016 11:12 AM -
It already exists in LINQ:
List<Users> _users = AllUsers.Where(u => u.Name.Contains('sam'));
- Proposed as answer by Wendy ZangMicrosoft contingent staff Thursday, August 25, 2016 1:33 AM
- Marked as answer by Kevin Linq Wednesday, September 7, 2016 2:17 AM
Wednesday, August 24, 2016 11:16 AM
All replies
-
Thank you folks.
I solved my problem. Here is the same code.
public static List<T> LikeSearch<T>(this List<T> data, string key, string searchString) { var property = typeof(T).GetProperty(key); if (property == null) throw new ArgumentException("'{typeof(T).Name}' does not implement a public get property named '{key}'."); return data.Where(d => ((string)property.GetValue(d)).Contains(searchString)).ToList(); }
Hope this will help you people.
- Proposed as answer by Wendy ZangMicrosoft contingent staff Thursday, August 25, 2016 1:32 AM
- Marked as answer by Kevin Linq Wednesday, September 7, 2016 2:17 AM
Wednesday, August 24, 2016 11:12 AM -
It already exists in LINQ:
List<Users> _users = AllUsers.Where(u => u.Name.Contains('sam'));
- Proposed as answer by Wendy ZangMicrosoft contingent staff Thursday, August 25, 2016 1:33 AM
- Marked as answer by Kevin Linq Wednesday, September 7, 2016 2:17 AM
Wednesday, August 24, 2016 11:16 AM