Skip to content

Instantly share code, notes, and snippets.

@tombatron
Created July 15, 2017 13:36
Show Gist options
  • Save tombatron/2c12d9750dd0894e0f4dbfae241bfca3 to your computer and use it in GitHub Desktop.
Save tombatron/2c12d9750dd0894e0f4dbfae241bfca3 to your computer and use it in GitHub Desktop.
GroupedDictionary
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