我还没有广泛使用它,但我肯定一直在关注它的用途,并在我们的代码库中寻找使用它的机会(不幸的是,我们的许多项目仍然受 .NET-2.0 约束暂且)。我自己想出的一个小宝石是一个独特的单词计数器。我认为这是我能想到的最快、最简洁的实现——如果有人能做得更好,那就太棒了:
private static readonly char[] delimiters = { ' ', '.', ',', ';', '\'', '-', ':', '!', '?', '(', ')', '<', '>', '=', '*', '/', '[', ']', '{', '}', '\\', '"', '\r', '\n' };
private static readonly Func<string, string> theWord = Word;
private static readonly Func<IGrouping<string, string>, KeyValuePair<string, int>> theNewWordCount = NewWordCount;
private static readonly Func<KeyValuePair<string, int>, int> theCount = Count;
private static void Main(string[] args)
{
foreach (var wordCount in File.ReadAllText(args.Length > 0 ? args[0] : @"C:\DEV\CountUniqueWords\CountUniqueWords\Program.cs")
.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
.AsParallel()
.GroupBy(theWord, StringComparer.OrdinalIgnoreCase)
.Select(theNewWordCount)
.OrderByDescending(theCount))
{
Console.WriteLine(
"Word: \""
+ wordCount.Key
+ "\" Count: "
+ wordCount.Value);
}
Console.ReadLine();
}
private static string Word(string word)
{
return word;
}
private static KeyValuePair<string, int> NewWordCount(IGrouping<string, string> wordCount)
{
return new KeyValuePair<string, int>(
wordCount.Key,
wordCount.Count());
}
private static int Count(KeyValuePair<string, int> wordCount)
{
return wordCount.Value;
}