【问题标题】:Remove duplicates from list based on multiple fields or columns根据多个字段或列从列表中删除重复项
【发布时间】:2015-04-27 06:09:33
【问题描述】:

我有一个 MyClass 类型的列表

public class MyClass
{
   public string prop1 {} 
   public int prop2 {} 
   public string prop3 {} 
   public int prop4 {} 
   public string prop5 {} 
   public string prop6 {} 
   ....
}

此列表将有重复项。我想从这个列表中查找并删除 prop1、prop2 和 prop3 重复的项目。其他属性是否重复无关紧要

这是我尝试过但不起作用的方法。

List<MyClass> noDups = myClassList.GroupBy(d => new {d.prop1,d.prop2,d.prop3} ).Where(g => g.Count() > 1).Select(g=> g.Key);

我不想为此使用任何第三方工具。只有纯 linq。

【问题讨论】:

  • 你说的不工作是什么意思?您收到任何异常或错误消息?结果是什么?
  • 我遇到异常无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“System.Collections.Generic.List”。存在显式转换(您是否缺少演员表?)
  • 将 ToList 放在 Select(g=> g.Key) 的末尾时...我得到“无法隐式转换类型'System.Collections.Generic.List'到'System.Collections.Generic.List'
  • 当我返回一个 var 类型并执行一个列表时,我只得到我放在 {} 括号内的字段。我也想要剩下的字段..

标签: c# linq deduplication


【解决方案1】:

这将为每个“类型”返回一个项目(如 Distinct)(因此,如果您有 A、A、B、C,它将返回 A、B、C)

List<MyClass> noDups = myClassList.GroupBy(d => new {d.prop1,d.prop2,d.prop3} )
                                  .Select(d => d.First())
                                  .ToList();

如果你只想要没有重复的元素(所以如果你有 A、A、B、C 它将返回 B、C):

List<MyClass> noDups = myClassList.GroupBy(d => new {d.prop1,d.prop2,d.prop3} )
                                  .Where(d => d.Count() == 1)
                                  .Select(d => d.First())
                                  .ToList();

【讨论】:

  • 如果您需要用datatable 而不是MyClass 做同样的事情怎么办?
  • @RehanKhan 完全不同的问题...问一个新问题,更容易。
  • 如果您有兴趣,here 就是那个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多