【问题标题】:How do I delete all values with duplicates from list? [duplicate]如何从列表中删除所有具有重复项的值? [复制]
【发布时间】:2021-03-22 21:08:03
【问题描述】:

我可以找到许多不同的删除重复项的方法,例如 LINQ“Distinct().ToList()”,但这仍然会留下具有重复项的值,但我想删除所有具有重复项的值。如果您有“1、2、3、3、4”的列表,我希望留下“1、2、4”。谢谢!

【问题讨论】:

  • 必须从原始列表中删除重复项,还是可以接受删除重复项的新列表?

标签: c# duplicates


【解决方案1】:

如果您更喜欢 Linq 解决方案,您可以尝试GroupBy 而不是Distinct

 var result = list
   .GroupBy(item => item)               // group items
   .Where(group => group.Count() == 1)  // keep groups with single item only
   .SelectMany(group => group)          // flatten groups to sequence of items
   .ToList();

如果您正在寻找 in place 解决方案(您想从 existing 列表中删除重复项):

  HashSet<int> duplicates = new HashSet<int>(list
    .GroupBy(item => item)
    .Where(group => group.Count() > 1)
    .Select(group => group.Key));

  int p = 0;

  for (int i = 0; i < list.Count; ++i) 
    if (!duplicates.Contains(list[i]))
      list[p++] = list[i];

  list.RemoveRange(p, list.Count - p);

【讨论】:

  • @JohnathanBarclay OP 想要删除重复项。 Distinct 没有这样做
  • 是的,我看错了问题。
  • 另一种选择:list.ToLookup(i =&gt; i).Where(x =&gt; x.Count() == 1).Select(x =&gt; x.Key)
【解决方案2】:

通过GroupBy,您可以找到所有重复项。使用Except,您可以找到所有不重复的条目:

List<int> output = input.Except(input.GroupBy(i => i).Where(g => g.Count() > 1).Select(g => g.Key)).ToList();

在线演示:https://dotnetfiddle.net/vTo4Cx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 2021-04-09
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多