【问题标题】:Using LINQ when my where clause will contain a LIST当我的 where 子句将包含 LIST 时使用 LINQ
【发布时间】:2013-05-15 01:30:57
【问题描述】:

我有一个尝试使用 LINQ 查询的列表。 T 类型有一个属性是 List 。我正在尝试查询我的 List 的 List 属性,以仅提取那些 List 属性项目与我为过滤而构建的单独 List 中的项目匹配的对象。我的代码如下所示:

class T {
   List<U> Names;
}

class U {

}

//then I want to query a List of T by interrogating which T objects' Names property has the same items that I have a List < U > that I have created.

List<U> searchTermItems;
List<T> allObjects;

//Query allObjects and find out which objects' Name property items match the items in the searchTermItems list

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    你可以使用Enumerable.Intersect

    var filtered = allObjects.Intersect(searchTermItems);
    

    因为您使用的是列表集合而不是单个列表,为了获得所需的输出,您需要将Enumerable.WhereEnumerable.Intersect 结合使用:

    var filtered = allObjects.Where(x => x.Names.Intersect(searchTermItems).Any());
    

    【讨论】:

    • allObjects 列表没有可以像这样相交的属性 - 不过,Where 应该这样做。类似Where(t =&gt; t.Names.Intersect(searchTermItems).Count() &gt; 0)
    • 编译器抱怨我正在使用 List 并且我需要使用 IQueryable 进行交叉。我需要在这里做什么?我是否需要将父级和属性列表强制转换为 IQuerable
    猜你喜欢
    • 1970-01-01
    • 2018-04-14
    • 2015-08-22
    • 1970-01-01
    • 2021-12-15
    • 2021-11-23
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    相关资源
    最近更新 更多