我想将动态lambda表达式传递给下面的函数,但我不确定如何在表达式对象上定义.take()或.orderByDescending()。
如果我想调用下面的函数,那么我想能够这样做:
dbprovider.Query = (x => x.ConfigurationReference == "172.16.59.175")
.Take(100)
.OrderByDescending(x.Date)
FindEntities(db, dbprovider.Query)
但我不能(这个语法无效)。有什么想法吗?
public static List<T> FindEntities<T>(TrackingDataContext dataContext, System.Linq.Expressions.Expression<Func<T, bool>> find) where T : class
{
try
{
var val = dataContext.GetTable<T>().Where(find).ToList<T>();
return val;
}
catch (Exception ex)
{
throw ex;
}
}
最佳答案
参数类型为:
System.Linq.Expressions.Expression<Func<T, bool>> find
这意味着它可以接受一个谓词(“where”子句),并且只能接受一个谓词。因此,你只能通过过滤器:
x => x.ConfigurationReference == "172.16.59.175"
若要执行所需的操作,需要在
FindEntities
中添加其余代码,使其成为:var val = dataContext.GetTable<T>().Where(find)
.OrderByDescending(x => x.Date).Take(100).ToList<T>();
(还要注意
Take
应该在OrderByDescending
之后)一种方法是:
public static List<T> FindEntities<T>(TrackingDataContext dataContext,
System.Linq.Expressions.Expression<Func<T, bool>> find,
Func<IQueryable<T>, IQueryable<T>> additonalProcessing = null
) where T : class
{
var query = dataContext.GetTable<T>().Where(find);
if(additonalProcessing != null) query = additonalProcessing(query);
return query.ToList<T>();
}
打电话给:
var data = FindEntities(db, x => x.ConfigurationReference == "172.16.58.175",
q => q.OrderByDescending(x => x.Date).Take(100));
但是,坦白地说,我不知道这会是什么意思…调用方可以在本地更方便地完成所有这些操作,而根本不使用
FindEntities
。只是:var data = db.GetTable<T>()
.Where(x => x.ConfigurationReference == "172.16.58.175")
.OrderByDescending(x => x.Date).Take(100).ToList();
甚至:
var data = db.SomeTable
.Where(x => x.ConfigurationReference == "172.16.58.175")
.OrderByDescending(x => x.Date).Take(100).ToList();
或者只是:
var data = (from row in db.SomeTable
where row.ConfigurationReference == "172.16.58.175"
orderby row.Date descending
select row).Take(100).ToList();