Skip to content

Commit

Permalink
task/dict extension
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasteles committed Jun 2, 2023
1 parent 4c92327 commit d567999
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/DictionaryExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;

/// <summary>
/// Dictionary Extensions
Expand Down Expand Up @@ -31,14 +34,19 @@ public static class DictionaryExtensions
this IEnumerable<IEnumerable<KeyValuePair<TKey, TValue>>> @this) where TKey : notnull
{
var result = new Dictionary<TKey, TValue>();
foreach (var (key, value) in @this.SelectMany())
{
if (result.ContainsKey(key))
result[key] = value;
else
result.Add(key, value);
}

foreach (var (key, value) in @this.SelectMany()) result[key] = value;
return result;
}

/// <summary>
/// Return a task waiting for each key on the dictionary
/// </summary>
[SuppressMessage("AsyncUsage",
"AsyncFixer02:Long-running or blocking operations inside an async method")]
public static async Task<IDictionary<TKey, TValue>> WhenAll<TKey, TValue>(
this IDictionary<TKey, Task<TValue>> @this) where TKey : notnull
{
await Task.WhenAll(@this.Values).ConfigureAwait(false);
return @this.ToDictionary(x => x.Key, x => x.Value.Result);
}
}

0 comments on commit d567999

Please sign in to comment.