我工作的地方,用户必须输入某种字符串的程序,并计划将其存储在一个列表或数组,然后计算项目是重复了多少遍.
然后以重复次数的降序显示最重复的三个项目(第一个有10个重复,第二个有9个,第三个有8个)
听起来很简单.由于我不知道有多少人会输入一个字符串,我使用了一个列表,然后按照这个例子:
foreach (string value in list.Distinct())
{
System.Diagnostics.Debug.WriteLine("\"{0}\" occurs {1} time(s).", value, list.Count(v => v == value));
}
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,.Distinct()不会出现在我的列表名称之后.我做错什么了吗?这与我的C#有关,这不是C#3.0吗?该示例从未提及有关添加其他引用等的任何内容.
有没有其他方法可以做到这一点?
Cᴏʀ*_*ᴏʀʏ 11
.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).", value, counts[value]);
}
Run Code Online (Sandbox Code Playgroud)