我有一个类,我想将数据列表传递给。我希望这个课程
我已将IQueryable
条件添加为我想要实现的伪代码。这可能吗?
internal class Problem
{
public IEnumerable<Vendor> Vendors { get; set; }
public IEnumerable<Class1> ReturnedData { get; set; }
public Problem(List<Class1> data, IQueryable condition)
{
Vendors = data.SelectMany(d => d.Vendors).Select(v => v.VendorName).Distinct().Select(v => new Vendor {VendorName = v}).ToList();
ReturnedData = data.AsQueryable().Where(condition);
}
}
internal class Class1
{
public IEnumerable<Vendor> Vendors { get; set; }
// lots of other stuff
}
internal class Vendor
{
public object VendorName { get; set; }
}
答案 0 :(得分:3)
我会略有不同。
首先安装nuget包System.Linq.Dynamic
Install-Package System.Linq.Dynamic
之后, `IQueryable&#39; s where函数将支持string作为参数。所以你可以这样做:
protected static IQueryable<T> ApplyGridFilter<T>(IQueryable<T> query)
{
var qText = "id == 1";
query = query.Where(qText);
return query;
}
好处是您可以轻松地在客户端建立where条件而无需创建Func<Class1, bool>>
答案 1 :(得分:2)
当调用IQuerable<T>.Where()
作为扩展方法时,它所采用的参数不是IQueryable
实例,而是谓词表达式:
public Problem(List<Class1> data, Expression<Func<Class1, bool>> condition)
{
Vendors = data.SelectMany(d => d.Vendors).Select(v => v.VendorName).Distinct()
.Select(v => new Vendor {VendorName = v}).ToList();
ReturnedData = data.AsQueryable().Where(condition);
}
现在,您可以在实例化Problem
类时创建各种过滤器:
var problemInstance = new Problem(data, x => x.VendorName == "Rob");
答案 2 :(得分:2)
我更喜欢只使用委托作为输入参数,并在调用类
中实现过滤器逻辑 class Problem{
public Problem(data, Func<data, IEnumerable<Class1>> delegate){
ReturnedData = delegate(data);
}
}
var problem = new Problem(data, ds => ds.where(d => d.name =="xyz").tolist());