Dictionary<string, int> statistics = words
.GroupBy(word => word)
.ToDictionary(
kvp => kvp.Key, // the word itself is the key
kvp => kvp.Count()); // number of occurences is the value
int isCount = statistics["is"]; // returns 2
EDIT:
我正在发布满足您的增强要求的代码。但对于未来,只需发布另一个问题,而不是修改已回答的问题!
// retrieving all duplicate words
string[] duplicates = statistics
.Where(kvp => kvp.Value > 1)
.Select(kvp => kvp.Key)
.ToArray();
// counting all duplicates and formatting it into a list in the desired output format
string output = String.Join(
"\n",
statistics
.Where(kvp => kvp.Value > 1)
.Select(kvp =>
String.Format(
"count(\"{0}\") = {1}",
kvp.Key,
kvp.Value))
.ToArray() // this line is only needed on older versions of .NET framework
);