gpt4 book ai didi

c# - LINQ 选择列表,其中子列表包含另一个列表中的项目

转载 作者:太空狗 更新时间:2023-10-29 22:06:09 25 4
gpt4 key购买 nike

我不知道如何创建此查询。如果项目 Cats 列表包含与 List2 中一只猫的 ID 匹配的 Cat 对象,我需要选择列表 1 中的项目。这可能吗?谢谢

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;
}

最佳答案

您可以只使用以下 LINQ 表达式:

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

你也应该能够用 intersect 来做到这一点(也就是说,如果你的类重写了它们的 Equals 方法来检查匹配的 ID - 请参阅 Intersect on MSDN ):

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

关于c# - LINQ 选择列表,其中子列表包含另一个列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35814049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com