简体   繁体   中英

LINQ select List where sub-list contains item from another list

I can't wrap my head around how to create this query. I need to select the items in List 1, if the items Cats list contains a Cat object matching the ID of one of the Cats in List2. Is this possible? Thank you

List1<pet> List1 = new List<pet>(100);
List2<cat> List2 = new List<cat>(30);

//populate lists, some of the items in List2 (cat) will be in the List1 items Cats list

//classes
class pet{
   string ID;
   List<cat> Cats;
}

class cat {
   string ID;
   string name;
}

You can just use following LINQ expression:

List1.Where(p => p.Cats.Any(c => List2.Any(c2 => c2.ID == c.ID)));

You should also be able to do that with intersect (That is if your classes have their Equals methods overriden to check for matching IDs - see Intersect on MSDN ):

List1.Where(p => p.Cats.Intersect(List2).Any())

这应该适用于嵌套的Any

var result = List1.Where(p => List2.Any(l => p.Cats.Any(c => c.ID == l.ID)));

尝试这个

var naughtycats = List1.Where(pet => List2.Select(cat => cat.ID).Contains(pet.ID));

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