Abhinaw Kaushik Abhinaw Kaushik - 4 years ago 83
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
return _list;

Uses will be like:

Example 1

List<Users> _users = LikeSearch<Users>(AllUsers,'Name','sam');

is the list of 100

Example 2

List<Customers> _cust = LikeSearch<Customers>(AllCustomers,'City','London');

is the list of 100

Please sugest

Answer Source

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}'.");

    return data.Where(d => property.GetValue(d).Equals(searchString)).ToList();

    return data.Where(d => ((string)property.GetValue(d)).Contains(searchString)).ToList();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download