【问题标题】:Check if a list contains all of another lists items when comparing on one property在比较一个属性时检查列表是否包含所有其他列表项
【发布时间】:2017-11-21 19:26:26
【问题描述】:

我正在学习 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 来做到这一点?

【问题讨论】:

  • 有什么原因你没有使用Contains
  • @NetMage 对于使用Contains,他应该覆盖Equals
  • 为了更清楚起见,对于随后阅读此内容的任何人,正在检查的是 list2 中的所有项目是否都可以在 list1 中找到。

标签: c# list linq any


【解决方案1】:
bool existsCheck = list1.All(x => list2.Any(y => x.SupplierId == y.SupplierId));

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

【讨论】:

  • Any() 接受谓词;这不会编译。
  • @SLaks fixed..是手工输入的 :)
  • 最易读的解决方案。为什么每个人都把事情复杂化?
  • 这个解决方案真的很有意义。我会推荐这个作为我的答案。
【解决方案2】:

您想检查list1 中是否有任何ID 不在list2 中:

if (list1.Select(p => p.SupplierId).Except(list2.Select(p => p.SupplierId)).Any())

【讨论】:

  • 我认为你有 list1list2 倒退。
  • @SLaks 我不确定这是否正确;如果将 List2 中的“4”更改为“5”,这是否仍会返回 true,而原始代码示例会返回 false?
  • 就像 NetMage 说他正在检查 List2 中是否有任何 ID 不在 List1 中,而不是反过来,所以我认为这些需要反转和一个“!”添加
【解决方案3】:

要查看list1 包含所有list2,请检查list1 中的Any 是否与list2 中的All 匹配:

private static bool CheckLists(List<Product> list1, List<Product> list2) => list2.All(l2p => list1.Any(l1p => l1p.SupplierId == l2p.SupplierId));

不过,我可能会写一个通用的扩展方法:

public static class Ext {
    static public bool ContainsAll<T, TKey>(this List<T> containingList, List<T> containee, Func<T, TKey> key) {
        var HSContainingList = new HashSet<TKey>(containingList.Select(key));
        return containee.All(l2p => HSContainingList.Contains(key(l2p)));
    }
    static public bool ContainsAll<T>(this List<T> containingList, List<T> containee) => containingList.ContainsAll(containee, item => item);
}

那么你可以这样称呼它:

var ans = list1.ContainsAll(list2, p => p.SupplierId);

【讨论】:

    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多