【问题标题】:Checking for duplicates in a complex object using Linq or Lambda expression使用 Linq 或 Lambda 表达式检查复杂对象中的重复项
【发布时间】:2008-10-21 20:32:50
【问题描述】:

我刚刚开始学习 linq 和 lambda 表达式,它们似乎非常适合在复杂对象集合中查找重复项,但我有点困惑,希望有人能帮助我重回正轨快乐编码。

我的对象的结构类似于 list.list.uniqueCustomerIdentifier

我需要确保整个复杂对象中没有重复的 uniqueCustomerIdentifier。如果有重复,我需要识别哪些重复并返回重复列表。

【问题讨论】:

    标签: linq lambda linq-to-objects


    【解决方案1】:
    • 解压层次结构
    • 将每个元素投影到其 uniqueID 属性
    • 将这些 ID 分组
    • 按包含 1 个以上元素的组过滤组
    • 将每个组投影到组的密钥(返回到 uniqueID)
    • 枚举查询并将结果存储在列表中。

    var result = 
      myList
        .SelectMany(x => x.InnerList)
        .Select(y => y.uniqueCustomerIdentifier)
        .GroupBy(id => id)
        .Where(g => g.Skip(1).Any())
        .Select(g => g.Key)
        .ToList()
    

    【讨论】:

    • 您可以跳过 .Select(y => y.uniqueCustomerIdentifier) 并改用 .GroupBy(y => y.uniqueCustomerIdentifier)。
    【解决方案2】:

    有一个 linq 运算符 Distinct( ),如果您只需要 id,它允许您过滤到一组不同的记录。如果你已经设置你的类来覆盖等于你或者有一个IEqualityComparer,你可以直接调用 Distinct 扩展方法来从列表中返回唯一的结果。另外,您还可以使用 Union 和 Intersect 方法在两个列表之间合并或过滤。

    另一种选择是按 id 分组,然后选择第一个元素。

    var results = from item in list
                  group item by item.id into g
                  select g.First();
    

    【讨论】:

      【解决方案3】:

      如果您想展平两个列表层次结构,请使用SelectMany 方法将IEnumerable<IEnumerable<T>> 展平为IEnumerable<T>

      【讨论】:

        猜你喜欢
        • 2013-03-08
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 2019-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多