Search code examples
c#linqlambdaexpressionfunc

Convert a filter expression based on property name and value to Linq Where clause Func<T, bool>?


I would like to create a method that will filter my data based on a property name and value a user passes to my method. Unfortunately I cannot change the interface the code uses and I am merely extending it by creating a new type of data class. Please see code what I mean:

public interface IService{
     Task<IEnumerable<T>> GetCollection<T>(string name, string fieldPath, string value)
}
public class MockService : IService
{
        MockDb _db = new Mock();
        public async Task<IEnumerable<T>> GetCollection<T>(string fieldPath, string value)
        {
            Func<T, bool> func = <WHAT CODE IS REQUIRED HERE BASED ON THE FIELD PATH AND VALUE?>;
            return _db.GetTable<T>(func);
        }
}

DATA CLASS:

public class MockDb{
       public List<T> GetTable<T>(Func<T, bool> func){
            return somecollection.Where(func).ToList();
       }
}

How can I convert the input to filter, i.e. fieldPath and value into a Func?


Solution

  • Here is a simple way to do it assuming that fieldPath is the name of property and the value is a string type:

     public async Task<IEnumerable<T>> GetCollection<T>(string fieldPath, string value)
     {
            return _db.GetTable<T>(t=> ((string) t.GetType().GetProperty(fieldPath).GetValue(t)) == value);
     }
    

    For, more generic and complex solution you should use Expression as suggested by Jonathan Barclay.