[英]How do i filter one list from another list using linq
I wrote the following query to filter query. 我写了以下查询来过滤查询。
I used First()
which is causing the issue I didn't notice earlier because Entity2
is also a collection. 我使用First()
导致了我之前没有注意到的问题,因为Entity2
也是一个集合。 It only filters the first Id. 它仅过滤第一个ID。
query = query.Where(x => filter.Ids.Contains(x.Entity2.Select(y => y.testId).First()));
Please suggest how I can use contains to check all testId property of Entity2 ? 请建议我如何使用包含检查Entity2的所有testId属性?
Basically x.Entity2.Select(y => y.testId) is list of Ids which i want to check whether they contains in filter.Ids or not. 基本上x.Entity2.Select(y => y.testId)是ID的列表,我要检查它们是否包含在filter.Ids中。
If I understand correctly, filter.Ids
and x.Entity2.Select(y => y.testId)
are both lists if Ids, and you want to make sure that all Ids from x.Entity2
are also in filter.Ids
. 如果我正确理解,则filter.Ids
和x.Entity2.Select(y => y.testId)
都列出了Ids,并且您要确保x.Entity2
中的所有ID也都在filter.Ids
。 In that case, you want the following: 在这种情况下,您需要以下内容:
var result = query.Where(x => x.Entity2.Count(y => filter.Ids.Contains(y.testId)) == x.Entity2.Count);
What we are doing here is we are counting for each element of query
, the number of Ids that are both in it's Entity2
and in filter.Ids
. 我们在这里所做的是为每个query
元素计数,即它的Entity2
和filter.Ids
的ID数量。 If that number is equal to the total number of Ids in Entity2
, then we include that in the result. 如果该数目等于Entity2
中Ids的Entity2
,则我们将其包括在结果中。
For your above query you can also use Any()
and Contains()
both , it will work as According to you filter is collection which has Ids and Entity2 both are also collection , so assuming that i wrote this, 对于您上面的查询,您还可以同时使用Any()
和Contains()
,它的工作方式如下:根据您的筛选器是具有IDs和Entity2的集合也是collection,因此假设我编写了此代码,
query = query.Where(x => filter.Where(a=> a.Entity2.Any(y=> a.Ids.Contains(y.testId));
but in your query also you can remove First()
and can use ToList()
but it will be throw OutofMemoryException
, if data is large. 但是在查询中,您也可以删除First()
并可以使用ToList()
但是如果数据很大,它将被抛出OutofMemoryException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.