【问题标题】:How to search for duplicates in an Enumerable list checking specific properties如何在检查特定属性的可枚举列表中搜索重复项
【发布时间】:2019-06-04 11:18:39
【问题描述】:

我有一个可枚举的对象列表。

该对象具有以下属性: -ID -姓名 -类型

我想收集那些在列表中具有相同名称和类型的对象的 ID。

【问题讨论】:

    标签: c# duplicates enumerable


    【解决方案1】:

    要在集合中搜索重复项(基于两个字段-Name and Type)并检索第三个字段 (ID),您需要首先将问题分解为多个部分。

    1) 查找重复项

    • GroupBy 键字段,(名称和类型)

    list.GroupBy(x=>new{x.Name,x.Type})

    • 过滤包含 1 个以上元素的组

    list.GroupBy(x=>new{x.Name,x.Type}).Where(x=>x.Count()>1)

    2) 选择 ID

    • 扁平化组

    list.GroupBy(x=>new{x.Name,x.Type}) .Where(x=>x.Count()>1) .SelectMany(x=>x.ToList())

    • 选择 ID

      list.GroupBy(x=>new{x.Name,x.Type}) .Where(x=>x.Count()>1) .SelectMany(x=>x.ToList()).Select(x=>x.ID)

    例如,将它们放在一起,

       var list = new List<CustomObject>
        {
            new CustomObject{ID=1, Name="Abc",Type="Type1"},
            new CustomObject{ID=2, Name="Def",Type="Type2"},
            new CustomObject{ID=3, Name="Abc",Type="Type1"},
            new CustomObject{ID=4, Name="Abc",Type="Type2"},
            new CustomObject{ID=5, Name="Def",Type="Type2"},
            new CustomObject{ID=6, Name="Def",Type="Type1"},
        };
    
        var result = list.GroupBy(x=>new{x.Name,x.Type})
                         .Where(x=>x.Count()>1)
                         .SelectMany(x=>x.ToList()).Select(x=>x.ID);
    

    上面例子的输出

    1 
    3 
    2 
    5 
    

    【讨论】:

      【解决方案2】:

      使用 Linq .GroupBy() 它将创建一个列表列表,其中每个列表都由一个键组织。

      list.GroupBy(e =&gt; new { e.Name, e.Type })

      【讨论】:

      • 为什么会被降级?我现在删除了我的答案,使用相同的方法,但可能过于详细。
      • 你只回答了部分问题
      【解决方案3】:

      使用 Linq 和 group 按名称和类型对所有对象进行分组,然后只取 Count > 1 的对象。

      var group = from myObject o in myObjects
                 group new { p.Name, p.Type } into grp
                 select new { Name = grp.Key.Name, Type = grp.Key.Type, Count = grp.Count() };
      
      var dups = group.Where(g=>g.Count >1);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-23
        • 2012-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-26
        相关资源
        最近更新 更多