当我的where子句包含LIST时使用LINQ(Using LINQ when my where clause will contain a LIST)

编程入门 行业动态 更新时间:2024-10-25 21:31:04
当我的where子句包含LIST时使用LINQ(Using LINQ when my where clause will contain a LIST)

我有一个List,我试图使用LINQ查询。 T类型具有List <U>的属性。 我试图查询我的List <T>的List <U>属性,只拉取那些List属性项与我为过滤构建的单独List <U>中的项匹配的对象。 我的代码如下所示:

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

I have a List that I am trying to query using LINQ. The T type has a property that is a List < U >. I am trying to query my List < T >'s List < U > property to pull only those objects who's List property items match the items in a seperate List < U > that I have built for filtering. My code looks like this:

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

最满意答案

你可以使用Enumerable.Intersect :

var filtered = allObjects.Intersect(searchTermItems);

因为您正在处理列表集合而不是单个列表,所以为了实现所需的输出,您需要使用Enumerable.Where与Enumerable.Intersect一起使用:

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

You could use Enumerable.Intersect:

var filtered = allObjects.Intersect(searchTermItems);

Because you are working with a collection of lists rather than a single list, in order to acheive the desired output you will need to use Enumerable.Where in conjunction with Enumerable.Intersect:

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

更多推荐

本文发布于:2023-07-26 19:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1280271.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子句   LIST   clause   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!