Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One possible method to group using the outcome of an asynchronous Task<string> and receive a grouping by string in C# is as follows:

  1. Define a list of Task<string> objects to represent the asynchronous operations that generate strings, e.g.:
List<Task<string>> tasks = new List<Task<string>>()
{
    GetStringAsync("foo"),
    GetStringAsync("bar"),
    GetStringAsync("baz"),
};
  1. Use the Task.WhenAll method to wait for all the tasks to complete asynchronously, and then extract the results using the Task.Result property, e.g.:
Task<string>[] results = await Task.WhenAll(tasks);
  1. Use LINQ's GroupBy method to group the results by the first character of each string, e.g.:
var groups = results.GroupBy(s => s[0]);
  1. Iterate over the groups and print out the key and the count of items in each group, e.g.:
foreach (var group in groups)
{
    Console.WriteLine("{0}: {1}", group.Key, group.Count());
}

This will produce output like the following:

f: 1
b: 2