c# - 如何使用带有动态查询的 LINQ 定义 SELECT TOP?

标签 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;
    }
}

最佳答案

参数类型:

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();

关于c# - 如何使用带有动态查询的 LINQ 定义 SELECT TOP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13677904/

相关文章:

c# - Azure Key Vault secret 访问间歇性无法连接并出现套接字异常

c# - IFile RepositoryProvider 处理上传的文件

c# - FluentMongo LINQ : How to query a sublist of a class

linq - Entity Framework 表之间的多重关系

c# - 如何合并两个列表并删除重复项

c# - 当窗口不再位于顶部时的 WPF 事件

c# - WCF REST 和 QueryString,错误的 UriTemplate?

mysql - 使用 max() 查询表会产生奇怪的结果

MySQL 根据另外两列的值自动递增 ID

sql - 如何在 SQL Server 中参数化带有特殊字符的查询?