Abhinaw Kaushik Abhinaw Kaushik - 3 months ago 7
C# Question

It is possible to create a generic search method where key is unknown

It is 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

Answer

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();
}
Comments