简体   繁体   中英

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. It only filters the first 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 ?

Basically x.Entity2.Select(y => y.testId) is list of Ids which i want to check whether they contains in filter.Ids or not.

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 . 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 . If that number is equal to the total number of Ids in Entity2 , then we include that in the result.

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,

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM