【问题标题】:In C#, how do I check for duplicate elements inside of a list, then print the name of the duplicate element?在 C# 中,如何检查列表中的重复元素,然后打印重复元素的名称?
【发布时间】:2020-02-04 17:54:16
【问题描述】:

我正在尝试按字母顺序对列表进行排序,然后在对列表进行排序后,打印列表中多次出现的任何元素的名称。

大多数谷歌搜索仅地址比较单独的列表。我知道您可以比较字符串和列表元素(在本例中是字符串),但我不确定如何比较这些字符串,因为它们在列表中。

using System;
using System.Collections.Generic;

namespace Challenge5alphabeticalOrderSorting
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            List<string> fruit = new List<string>()
            {
                "apple",
                "mango",
                "mango",
                "orange",
                "blueberry",
                "blueberry"
            };

            fruit.Sort();
            foreach (string f in fruit)
                Console.WriteLine(f);
        }
    }
}

【问题讨论】:

  • 你可以使用 Linq,GroupBy() 然后 Select() where Count() &gt; 1
  • 比较 [i][i + 1]
  • fruit.GroupBy(name=&gt;name, (k,g)=&gt;new{ Name=k, Count=g.Count() }) .Where(g=&gt;g.Count&gt;1) .OrderByDescending(g=&gt;g.Count) .Dump(); 见:share.linqpad.net/m8to6t.linq
  • 这能回答你的问题吗? C# LINQ find duplicates in List

标签: c# list sorting compare


【解决方案1】:

下面的代码使用GroupByWhereCount 方法打印重复的名称,就像OP 想要的那样(不是计数或其他)

打印列表中出现次数超过的任何元素的名称 一次。

var groups = fruit.GroupBy(f => f).Where(g => g.Count() > 1);
foreach (var group in groups)
    Console.WriteLine(group.Key);

【讨论】:

    猜你喜欢
    • 2019-02-03
    • 2015-06-24
    • 1970-01-01
    • 2022-07-19
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多