Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

generics

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

like image 327
Abhinaw Kaushik Avatar asked Aug 24 '16 10:08

Abhinaw Kaushik


1 Answers

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();
}
like image 191
InBetween Avatar answered Nov 08 '22 18:11

InBetween