Skip to content

Instantly share code, notes, and snippets.

@erdomke
Created March 1, 2017 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save erdomke/dc96a03051102128bc0da3c0cf0d90bd to your computer and use it in GitHub Desktop.
Save erdomke/dc96a03051102128bc0da3c0cf0d90bd to your computer and use it in GitHub Desktop.
Special dictionary for aggregating values
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Special dictionary for aggregating values
/// </summary>
public class Aggregator<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>
{
private Dictionary<TKey, TValue> _values = new Dictionary<TKey, TValue>();
public TValue this[TKey key]
{
get
{
TValue existing;
if (_values.TryGetValue(key, out existing))
return existing;
return default(TValue);
}
set
{
_values[key] = value;
}
}
public bool ContainsKey(TKey key)
{
return _values.ContainsKey(key);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _values.GetEnumerator();
}
public void Remove(TKey key)
{
_values.Remove(key);
}
public void Update(TKey key, Func<TValue, TValue> func)
{
TValue existing;
if (_values.TryGetValue(key, out existing))
_values[key] = func(existing);
else
_values[key] = func(default(TValue));
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment