如何使用LINQ和动态查询定义SELECT TOP?

时间:2012-12-03 05:55:25

标签: c# sql linq lambda

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

1 个答案:

答案 0 :(得分: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();