Search code examples
c#.netgenericsreflectionasqueryable

Reflection to Filter List<T>


I am new to Reflection so please excuse my noob question. How can I create a Method that takes two Parameters, a Generic List and a String and then finds all items in that List where any property value matches the string.

So for example we have an object with 3 properties, I pass a list of this object to the method and a search string and it returns back a list of objects where any of the properties may contain the search string.

I can do like this :

var temp = list.AsQueryable().Where("SomeField == 1").Select("it");

But how can I make this method Generic so I can pass any List of Objects to it ?

Thanks in advance...


Solution

  • If you are using Dynamic Linq, try this

    public static IEnumerable<T> Filter<T>(IEnumerable<T> source, string searchStr)
    {
        var propsToCheck = typeof (T).GetProperties().Where(a => a.PropertyType == typeof(string));
    
        var filter = propsToCheck.Aggregate(string.Empty, (s, p) => (s == string.Empty ? string.Empty : string.Format("{0} OR ", s)) + string.Format("{0} == @0", p.Name));
    
        var filtered = source.AsQueryable().Where(filter, searchStr);
        return filtered;
    }