5

我想将动态 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;
    }
}
4

1 回答 1

6

参数类型为:

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();
于 2012-12-03T06:17:15.510 回答