Is it possible to create a generic search method where key is unknown? for e.g Key for the List will be passed to the parameter and it performs a like search and return the filtered List.
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
Assuming key
always refers to a public property implemented by whatever type T
is, you could do the following:
public static List<T> LikeSearch<T>(this List<T> data, string key, string searchString)
{
var property = typeof(T).GetProperty(key, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance);
if (property == null)
throw new ArgumentException($"'{typeof(T).Name}' does not implement a public get property named '{key}'.");
//Equals
return data.Where(d => property.GetValue(d).Equals(searchString)).ToList();
//Contains:
return data.Where(d => ((string)property.GetValue(d)).Contains(searchString)).ToList();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With