Anyone know of a good implementation of a MultiValueDictionary? Basically, I want something that allows multiple values per key. I want to be able to do somethi
Yet here's my attempt using ILookup and an internal KeyedCollection. Make sure the key property is immutable.
Cross posted here.
public class Lookup : Collection, ILookup
{
public Lookup(Func keyForItem)
: base((IList)new Collection(keyForItem))
{
}
new Collection Items => (Collection)base.Items;
public IEnumerable this[TKey key] => Items[key];
public bool Contains(TKey key) => Items.Contains(key);
IEnumerator>
IEnumerable>.GetEnumerator() => Items.GetEnumerator();
class Collection : KeyedCollection
{
Func KeyForItem { get; }
public Collection(Func keyForItem) => KeyForItem = keyForItem;
protected override TKey GetKeyForItem(Grouping item) => item.Key;
public void Add(TElement item)
{
var key = KeyForItem(item);
if (Dictionary != null && Dictionary.TryGetValue(key, out var collection))
collection.Add(item);
else
Add(new Grouping(key) { item });
}
public bool Remove(TElement item)
{
var key = KeyForItem(item);
if (Dictionary != null && Dictionary.TryGetValue(key, out var collection)
&& collection.Remove(item))
{
if (collection.Count == 0)
Remove(key);
return true;
}
return false;
}
}
class Grouping : Collection, IGrouping
{
public Grouping(TKey key) => Key = key;
public TKey Key { get; }
}
}