diff --git a/Extensions/MyCollections.cs b/Extensions/MyCollections.cs index a6b8a29..2c9b2c9 100644 --- a/Extensions/MyCollections.cs +++ b/Extensions/MyCollections.cs @@ -298,6 +298,27 @@ public static TValue GetOrAdd(this IDictionary return source[key]; } + /// + /// Creates a Bucket collection (Dictionary with List values) from a collection + /// of values and a function that selects the key for each value. + /// + public static Dictionary ConvertToBucket( this IEnumerable source, + Func GetKeyFromValue) where TArg : IList { + + Dictionary result = new Dictionary(source.Count()); + foreach(TValue value in source) { + TKey key = GetKeyFromValue(value); + if(result.TryGetValue(key, out TArg arg)) { + arg.Add(value); + } else { + TArg newArg = (TArg)Activator.CreateInstance(typeof(TArg)); + newArg.Add(value); + result[key] = newArg; + } + } + return result; + } + /// /// Performs an action on each element of a collection. /// @@ -495,4 +516,4 @@ public static IList Shuffle(this IList source) return source; } } -} \ No newline at end of file +}