【问题标题】:How to use a string in the linq where clause?如何在 linq where 子句中使用字符串?
【发布时间】:2012-03-28 23:56:56
【问题描述】:

我正在尝试将 Linq 查询作为字符串发送到要在 where 子句中使用的方法。由于 IEnumerable 对此不起作用,我已将 IEnumerable 转换为 IQueryable ,但它仍然会引发错误。以下是代码:

public static void  FilterData(string Query)
        {
            if((List<MemberMaintenanceData>)HttpContext.Current.Session["Allmembers"] != null)
            {
                //Get the IEnumerable object colection from session
                var data = (List<MemberMaintenanceData>) HttpContext.Current.Session["Allmembers"];
                //Convert it to IQueryable
                IQueryable<MemberMaintenanceData> queryData = data.AsQueryable();
                //This line doesn't compile!!
                queryData = queryData.Where(Query);
                HttpContext.Current.Session["Allmembers"] = queryData.AsEnumerable().ToList();
            }

        }

我打算将“a => a.AccountId == 1000”作为查询传递

【问题讨论】:

    标签: linq dynamic


    【解决方案1】:

    Microsoft 提供了一个免费(和开源)库,用于将字符串解析为 Lambda 表达式,然后可以在 Linq 查询中使用。它还包含标准查询运算符的版本,例如接受字符串参数的 Where()。你可以找到它described in Scott Guthries blog post on Dynamic Linq.

    例如,您可以执行这样的查询(改编自 Scott Guthrie 链接的 sn-p)

    // imagine these have come from a drop down box or some other user input...
    string thingToSelectBy = "City";
    string citySelectedByUser = "London";
    int minNumberOfOrders = 10;
    
    string whereClause = String.Format("{0} = @0 and Orders.Count >= @1", thingToSelectBy);
    
    var query = db.Customers
           .Where(whereClause, citySelectedByUser, minNumberOfOrders)
           .OrderBy("CompanyName")
           .Select("new(CompanyName as Name, Phone");
    

    此代码 sn-p 中的 Where 子句显示了如何使用参数化字符串创建 where 子句,然后在运行时动态注入参数值,例如,根据用户输入。这适用于任何类型的参数。

    在您的示例中,where 子句将是

    whereClause = "AccountId = 1000";
    

    所以实际上你会做类似的事情

    var newFilteredQueryData = queryData.Where("AccountId = 1000");
    

    该链接还包含您可以下载源代码的位置以及描述动态查询 API 和表达式语言的综合文档。

    【讨论】:

    • 动态 linq 库仅适用于整数而不适用于字符串,或者至少我没有看到任何使用字符串的示例。关于这个主题的文章和博客有很多,而且都以整数为例!我要查询的 AccountId 是一个字符串。
    • 我不确定您所说的“仅适用于整数而不适用于字符串”是什么意思。如果您查看动态查询语言的文档,您会发现它适用于任何类型——不仅仅是整数。在我建议的链接顶部附近的 API 文档截图中,它显示了使用字符串的示例。我稍微更新了我的答案以显示这一点。
    【解决方案2】:

    给定一个类,例如:

    public class foo
    {
      public int AccountID {get;set;}
    }
    

    你应该可以做这样的事情:

    Expression<Func<foo, bool>> filter = f => f.AccountID == 1000;
    

    然后将其作为您的查询传递。如果真的需要它作为字符串,你可以这样做:

    filter.ToString();
    

    【讨论】:

      【解决方案3】:

      //通过使用这个库

      使用 System.Linq.Dynamic.Core;

      InventoryList = Repository.GetAll(); // 可查询

      string filterString = "UnitPrice > 10 And Qty>100 OR Description.Contains("Dairy")";

      var filteredGenericList = InventoryList.Where(filterString);

      【讨论】:

        猜你喜欢
        • 2021-12-29
        • 2016-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-21
        • 1970-01-01
        相关资源
        最近更新 更多