Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion Extensions/MyCollections.cs
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,27 @@ public static TValue GetOrAdd<TKey, TValue, TArg>(this IDictionary<TKey, TValue>
return source[key];
}

/// <summary>
/// Creates a Bucket collection (Dictionary with List values) from a collection
/// of values and a function that selects the key for each value.
/// </summary>
public static Dictionary<TKey, TArg> ConvertToBucket<TKey, TValue, TArg>( this IEnumerable<TValue> source,
Func<TValue, TKey> GetKeyFromValue) where TArg : IList<TValue> {

Dictionary<TKey, TArg> result = new Dictionary<TKey, TArg>(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;
}

/// <summary>
/// Performs an action on each element of a collection.
/// </summary>
Expand Down Expand Up @@ -495,4 +516,4 @@ public static IList<T> Shuffle<T>(this IList<T> source)
return source;
}
}
}
}