获取在C#中重复项目的次数

前端之家收集整理的这篇文章主要介绍了获取在C#中重复项目的次数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个程序,用户必须在其中输入某种字符串,程序会将其存储在List或Array中,然后计算该项重复的次数.

然后以重复次数的降序显示最重复的三个项目(第一个有10个重复,第二个有9个,第三个有8个)

听起来很简单.由于我不知道有多少人会输入一个字符串,我使用了一个列表,然后按照这个例子:

foreach (string value in list.Distinct())  
{  
    System.Diagnostics.Debug.WriteLine("\"{0}\" occurs {1} time(s).",value,list.Count(v => v == value));  
}

但由于某种原因,.Distinct()不会出现在我的列表名称之后.我做错什么了吗?这与我的C#有关,这不是C#3.0吗?该示例从未提及有关添加其他引用等的任何内容.

有没有其他方法可以做到这一点?

解决方法

.Distinct()是LINQ扩展方法.您需要.NET 3.5才能使用它.

话虽如此,你不需要LINQ做你想要的.您可以轻松使用其他集合类和一些算术来获得结果.

// Create a dictionary to hold key-value pairs of words and counts
IDictionary<string,int> counts = new Dictionary<string,int>();

// Iterate over each word in your list
foreach (string value in list)
{
    // Add the word as a key if it's not already in the dictionary,and
    // initialize the count for that word to 1,otherwise just increment
    // the count for an existing word
    if (!counts.ContainsKey(value))
        counts.Add(value,1);
    else
        counts[value]++; 
}

// Loop through the dictionary results to print the results
foreach (string value in counts.Keys)
{
    System.Diagnostics.Debug
        .WriteLine("\"{0}\" occurs {1} time(s).",counts[value]);
}

猜你在找的C#相关文章