Created
July 15, 2017 13:36
-
-
Save tombatron/2c12d9750dd0894e0f4dbfae241bfca3 to your computer and use it in GitHub Desktop.
GroupedDictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class GroupedDictionary<TKey, TValue> : Dictionary<TKey, ICollection<TValue>> | |
{ | |
private readonly Func<TValue, TKey> _groupingKeyExtractor; | |
public GroupedDictionary(IEnumerable<TValue> values, Expression<Func<TValue, TKey>> groupingKey) | |
{ | |
_groupingKeyExtractor = groupingKey.Compile(); | |
PopulateDictionary(values); | |
} | |
public GroupedDictionary<TResultKey, TValue> GetGroupedDictionaryAt<TResultKey>(TKey key, Expression<Func<TValue, TResultKey>> groupingKey) | |
{ | |
return new GroupedDictionary<TResultKey, TValue>(this[key], groupingKey); | |
} | |
private void PopulateDictionary(TValue valueToAdd) | |
{ | |
var key = _groupingKeyExtractor(valueToAdd); | |
if (ContainsKey(key)) | |
{ | |
this[key].Add(valueToAdd); | |
} | |
else | |
{ | |
this[key] = new Collection<TValue> { valueToAdd }; | |
} | |
} | |
private void PopulateDictionary(IEnumerable<TValue> valuesToAdd) | |
{ | |
foreach (var valueToAdd in valuesToAdd) | |
{ | |
PopulateDictionary(valueToAdd); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment