gpt4 book ai didi

c# - 在比较一个属性时检查列表是否包含所有其他列表项

转载 作者:行者123 更新时间:2023-11-30 13:18:45 24 4
gpt4 key购买 nike

我正在学习 Linq,我有两个对象列表。我想将这些列表中的一个与另一个进行比较,以查看其中对象的所有属性是否都可以与另一个列表中的对象相匹配。因此,我为此提供了代码,但我想将其更改为 Linq 表达式。

var list1 = new List<Product>
{
new Product{SupplierId = 1,ProductName = "Name1"},
new Product{SupplierId = 2,ProductName = "Name2"},
new Product{SupplierId = 3,ProductName = "Name3"},
new Product{SupplierId = 4,ProductName = "Name4"}
};

var list2 = new List<Product>
{
new Product {SupplierId = 1,ProductName = "Name5"},
new Product {SupplierId = 4,ProductName = "Name6"}
};

private static bool CheckLists(List<Product> list1, List<Product> list2)
{
foreach (var product2 in list2)
{
bool result = false;
foreach (var product in list1)
{
if (product.SupplierId == product2.SupplierId)
{
result = true;
break;
}
}
if (!result)
{
return false;
}
}
return true;
}

我如何使用 LINQ 完成此操作?

最佳答案

bool existsCheck = list1.All(x => list2.Any(y => x.SupplierId == y.SupplierId));

会告诉您 list1 的所有项目是否都在 list2 中。

关于c# - 在比较一个属性时检查列表是否包含所有其他列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47421110/

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