我正在开发一个程序,用户必须在其中输入某种字符串,程序将其存储在列表或数组中,然后计算该项重复的次数。
重复次数最多的三项按重复次数降序显示(第一项重复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+才能使用它。
话虽如此,你不需要林肯做你想做的事。您可以很容易地使用其他集合类和一些算术来获得结果。
// 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]);
}