C# LINQ中的动态WHERE子句

C# LINQ中的动态WHERE子句,c#,linq,dynamic,where-clause,C#,Linq,Dynamic,Where Clause,将动态WHERE子句组装到LINQ语句的最佳方法是什么 我在表单上有几十个复选框,并将它们作为:Dictionary(Dictionary)传递回我的LINQ查询 public IOrderedQueryable<ProductDetail> GetProductList(string productGroupName, string productTypeName, Dictionary<string,List<string>> filterDictiona

将动态WHERE子句组装到LINQ语句的最佳方法是什么

我在表单上有几十个复选框,并将它们作为:Dictionary(Dictionary)传递回我的LINQ查询

public IOrderedQueryable<ProductDetail> GetProductList(string productGroupName, string productTypeName, Dictionary<string,List<string>> filterDictionary)
{
    var q = from c in db.ProductDetail
            where c.ProductGroupName == productGroupName && c.ProductTypeName == productTypeName
            // insert dynamic filter here
            orderby c.ProductTypeName
            select c;
    return q;
}
public IOrderedQueryable GetProductList(string productGroupName、string productTypeName、Dictionary filterDictionary)
{
var q=来自db.ProductDetail中的c
其中c.ProductGroupName==ProductGroupName&&c.ProductTypeName==ProductTypeName
//在此处插入动态过滤器
orderby c.ProductTypeName
选择c;
返回q;
}

(来源:)

你需要这样的东西吗?使用(下载包括示例)


查看更多示例。

您还可以使用LinqKit中的PredicateBuilder,使用或和链接多个类型安全lambda表达式


如果列的类型像字符串一样简单,则可以使用一种简单的方法

public static IEnumerable<MyObject> WhereQuery(IEnumerable<MyObject> source, string columnName, string propertyValue)
{
   return source.Where(m => { return m.GetType().GetProperty(columnName).GetValue(m, null).ToString().StartsWith(propertyValue); });
}
公共静态IEnumerable WhereQuery(IEnumerable源、字符串列名、字符串属性值)
{
返回source.Where(m=>{return m.GetType().GetProperty(columnName).GetValue(m,null).ToString().StartsWith(propertyValue);});
}
您可以使用Any()扩展方法。以下内容似乎对我有用

XStreamingElement root = new XStreamingElement("Results",
                from el in StreamProductItem(file)
                where fieldsToSearch.Any(s => el.Element(s) != null && el.Element(s).Value.Contains(searchTerm))
                select fieldsToReturn.Select(r => (r == "product") ? el : el.Element(r))
            );
            Console.WriteLine(root.ToString());

其中“fieldsToSearch”和“fieldsToReturn”都是列表对象。

CodePlex上的这个项目有您想要的

系统Linq.Dynamic-

项目说明

扩展System.Linq.Dynamic以支持对实体框架或任何支持IQueryable的提供程序执行字符串中定义的Lambda表达式

由于它是源代码的扩展,您可以在上面找到它,它将允许您执行以下操作:

诸如此类:


我想出了一个连我自己都能理解的解决方案。。。通过使用“Contains”方法,您可以链接任意多个位置。如果WHERE是空字符串,则忽略它(或将其计算为全选)。下面是我在LINQ中连接两个表的示例,应用多个where子句并填充要返回到视图的模型类。(这是一个全选)


我有一个类似的场景,需要根据用户输入添加过滤器,并链接where子句

下面是示例代码

var votes = db.Votes.Where(r => r.SurveyID == surveyId);
if (fromDate != null)
{
    votes = votes.Where(r => r.VoteDate.Value >= fromDate);
}
if (toDate != null)
{
    votes = votes.Where(r => r.VoteDate.Value <= toDate);
}
votes = votes.Take(LimitRows).OrderByDescending(r => r.VoteDate);
var-voces=db.voces.Where(r=>r.SurveyID==SurveyID);
if(fromDate!=null)
{
投票=投票。其中(r=>r.VoteDate.Value>=fromDate);
}
如果(toDate!=null)
{
投票数=投票数,其中(r=>r.VoteDate.Value r.VoteDate);

如果有人感兴趣,这就是我提出的解决方案


首先,我们确定我们需要使用的单个元素类型(TRow为DataRow),然后确定我们正在使用的“源”,并将标识符绑定到该源((源为TypedTableBase(OfTrow))。然后,我们必须指定谓词,或将要传递的WHERE子句(谓词为Func(OfTrow,Boolean))它将返回true或false。然后,我们确定希望返回的信息如何排序(OrderByField为字符串)。然后,我们的函数将返回EnumerableRowCollection(Of TRow),即满足谓词条件的数据行集合(EnumerableRowCollection(Of TRow))。这是一个基本示例。当然,您必须确保您的订单字段不包含空值,或者已正确处理该情况,并确保您的列名(如果您使用的是强类型数据源,请不要介意,它将为您重命名列)是标准的。

使用三元运算符动态确定是否包含条件似乎越来越简单

List productList=新列表()


只是想和大家分享我对这个案子的看法

另一种解决办法是:


public IOrderedQueryable GetProductList(string productGroupName, string productTypeName, Dictionary> filterDictionary)
{
    return db.ProductDetail
        .where
        (
            p =>
            (
                (String.IsNullOrEmpty(productGroupName) || c.ProductGroupName.Contains(productGroupName))
                && (String.IsNullOrEmpty(productTypeName) || c.ProductTypeName.Contains(productTypeName))
                // Apply similar logic to filterDictionary parameter here !!!
            )
        );  
}

这种方法非常灵活,允许任何参数为空。

github()上有一个移植版本,我参与并帮助管理。最适合我的需要且易于使用。谢谢。精彩的答案!!欢迎提供指向解决方案的链接,但请确保您的答案在没有它的情况下是有用的:这样您的其他用户就会知道它是什么以及为什么存在,然后引用您链接到的页面中最相关的部分,以防出现问题获取页面不可用。我很抱歉。我是新来的。除了字符串之外,还可以执行其他操作吗?我有相同的问题(),并且@tvanfosson告诉了我关于Dynamic Linq()。
        productList =
                db.ProductDetail.Where(p => p.ProductDetailID > 0 //Example prop
                && (String.IsNullOrEmpty(iproductGroupName) ? (true):(p.iproductGroupName.Equals(iproductGroupName)) ) //use ternary operator to make the condition dynamic
                && (ID == 0 ? (true) : (p.ID == IDParam))
                ).ToList();

public IOrderedQueryable GetProductList(string productGroupName, string productTypeName, Dictionary> filterDictionary)
{
    return db.ProductDetail
        .where
        (
            p =>
            (
                (String.IsNullOrEmpty(productGroupName) || c.ProductGroupName.Contains(productGroupName))
                && (String.IsNullOrEmpty(productTypeName) || c.ProductTypeName.Contains(productTypeName))
                // Apply similar logic to filterDictionary parameter here !!!
            )
        );  
}