【发布时间】: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()whereCount() > 1 -
比较
[i]和[i + 1]。 -
fruit.GroupBy(name=>name, (k,g)=>new{ Name=k, Count=g.Count() }) .Where(g=>g.Count>1) .OrderByDescending(g=>g.Count) .Dump();见:share.linqpad.net/m8to6t.linq -
这能回答你的问题吗? C# LINQ find duplicates in List