【问题标题】:Convert a filter expression based on property name and value to Linq Where clause Func<T, bool>?将基于属性名称和值的过滤器表达式转换为 Linq Where 子句 Func<T, bool>?
【发布时间】:2020-10-13 07:57:19
【问题描述】:

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

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?

【问题讨论】:

  • 看来您使用的是Entity Framework,在这种情况下,您应该使用可以转换为SQL的Expression&lt;Func&lt;T, bool&gt;&gt;。表达式可以动态构建;一个例子可以在这里找到:stackoverflow.com/questions/5094489/…
  • 在这种情况下不是,但我之前使用过 Expression>。这只是静态对象的 Mock Db。不过非常感谢。

标签: c# linq lambda expression func


【解决方案1】:

这是一个简单的方法,假设 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。

【讨论】:

  • 不需要转换为string;你可以使用Equals:t =&gt; t.GetType().GetProperty(fieldPath).GetValue(t).Equals(value)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多