Using Linq to filter by List<ListItem>

本文关键字:lt ListItem gt List Linq to filter by Using | 更新日期: 2023-09-27 18:01:00

我正试图用额外的搜索条件扩展我的linq查询,通过向函数发送List<Listitem>进行处理来过滤数据。该列表可以包含一个或多个项目,目的是检索符合任何标准的所有项目。由于我向函数发送了几个搜索条件,所以我向过滤器发送的信息越多,目标就是获得更准确的过滤器结果。如果一个或多个标准为空,则过滤器将获得不太准确的结果。每次执行以下代码时都会引发异常,我不知道如何解决using语句以包含List<ListItem>。感谢所有提前提供的帮助!

异常:Unable to create a constant value of type 'System.Web.UI.WebControls.ListItem'. Only primitive types or enumeration types are supported in this context.

using (var db = new DL.ENTS())
{
    List<DL.PRODUCTS> products = 
    (from a in db.PRODUCTS
      where (description == null || description == "" || 
            a.DESCRIPTION.Contains(description)) &&
            (active == null || active == "" || a.ACTIVE.Equals(active, StringComparison.CurrentCultureIgnoreCase)) &&
            (mID == null || mID == "" || a.MEDIA_ID == mID) &&
            (mID == null || objTypes.Any(s => s.Value == a.OBJECTS)) //Exception here!
      select a).ToList<DL.PRODUCTS>();
    return products;
}

Using Linq to filter by List<ListItem>

将基元值集合传递给表达式:

using (var db = new DL.ENTS())
{
    var values = objTypes.Select(s => s.Value).ToArray();
    List<DL.PRODUCTS> products = 
        (from a in db.PRODUCTS
         where (description == null || description == "" || a.DESCRIPTION.Contains(description)) &&
               (active == null || active == "" || a.ACTIVE.Equals(active, StringComparison.CurrentCultureIgnoreCase)) &&
               (mID == null || mID == "" || a.MEDIA_ID == mID) &&
               (mID == null || values.Contains(a.OBJECTS)) 
         select a).ToList<DL.PRODUCTS>();
    return products;
}

这将生成SQL IN子句。


注意-您可以使用lambda语法通过添加基于某些条件的过滤器来组成查询:

 var products = db.PRODUCTS;
 if (!String.IsNullOrEmpty(description))
     products = products.Where(p => p.DESCRIPTION.Contains(description));
 if (!String.IsNullOrEmpty(active))
     products = products.Where(p => p.ACTIVE.Equals(active, StringComparison.CurrentCultureIgnoreCase)));
 if (!String.IsNullOrEmpty(mID))
     products = products.Where(p => p.MEDIA_ID == mID);
 if (mID != null)
     products = products.Where(p => values.Contains(p.OBJECTS));
 return products.ToList();

Linq无法将ListItem上的谓词转换为对Sql有用的谓词。

我建议您先将ListItems的值预先投影到一个简单的List<string>中,然后再将其与Contains(转换为IN(一起使用

var listValues = objTypes.Select(_ => _.Value).ToList();
   List<DL.PRODUCTS> products = ...
   listValues.Contains(a.OBJECTS))