C#列表中重复项的计数

Mat*_*ron 2 c# linq arrays list counting

我想知道如何计算winform应用程序中C#中列表中的所有重复字符串.

List<string> colorList = new List<string> { "red", "red", "yellow", "blue", "blue", "orange", "green", "red" };
Run Code Online (Sandbox Code Playgroud)

例如,我有上面的列表,计数将是5,因为"红色"出现3次,"蓝色"出现两次.

很高兴使用循环或LINQ或任何必要的东西.

在我的实际程序中,这个列表可以包含1000个条目,因此性能也需要考虑.

谢谢!

Kla*_*ter 8

如果您只需要总数:

var total = colorList.GroupBy(_ => _).Where(_ => _.Count() > 1).Sum(_ => _.Count());
Run Code Online (Sandbox Code Playgroud)

大数据集可能更快的替代方案:

var hashset = new HashSet<string>(); // to determine if we already have seen this color
var duplicates = new HashSet<string>(); // will contain the colors that are duplicates
var count = 0;
foreach (var color in colorList)
{
    if (!hashset.Add(color))
    {
        count++;
        if (duplicates.Add(color))
            count++;
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:使用2 ^ 25(约3000万)条目列表测量两种方法:第一个3.7秒,第二个3.2秒.


Tan*_*jel 5

如果您只需要重复项的计数:

 List<string> colorList = new List<string> { "red", "red", "yellow", "blue", "blue", "orange", "green", "red" };

 var count = colorList.GroupBy(item => item)
                      .Where(item => item.Count() > 1)
                      .Sum(item => item.Count());
Run Code Online (Sandbox Code Playgroud)

试试这个逐项详细信息:

var result = colorList.GroupBy(item => item)
                      .Select(item => new
                          {
                              Name = item.Key,
                              Count = item.Count()
                          })
                      .OrderByDescending(item => item.Count)
                      .ThenBy(item => item.Name)
                      .ToList();
Run Code Online (Sandbox Code Playgroud)