将基于属性名称和值的过滤器表达式转换为Linq Where子句Func <T,bool>?

问题描述

我想创建一个方法,该方法将根据属性名称用户传递给我的方法的值来过滤数据。不幸的是,我无法更改代码使用的接口,而只是通过创建一种新型的数据类来扩展它。请查看代码我的意思:

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

数据类:

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

如何将输入转换为过滤器,即将fieldpath和value转换为Func?

解决方法

这是一种简单的方法,假设fieldPath是属性的名称,而值是字符串类型:

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

对于更通用,更复杂的解决方案,您应该使用Jonathan Barclay建议的Expression。