Skip to content

Instantly share code, notes, and snippets.

@ilya-g
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilya-g/e5661991f1636a745d1b to your computer and use it in GitHub Desktop.
Save ilya-g/e5661991f1636a745d1b to your computer and use it in GitHub Desktop.
public static CastLookup<TKey, TElement> Cast<TKey, TElement>(this ILookup<TKey, TElement> lookup)
{
return new CastLookup<TKey,TElement>(lookup);
}
public class CastLookup<TKey, TElement>
{
private readonly ILookup<TKey, TElement> lookup;
public CastLookup(ILookup<TKey, TElement> lookup)
{
this.lookup = lookup;
}
public ILookup<TKey, TNewElement> To<TNewElement>()
{
return new Lookup<TNewElement>(this.lookup);
}
private class Lookup<TNewElement> : ILookup<TKey, TNewElement>
{
private readonly ILookup<TKey, TElement> innerLookup;
private class Grouping: IGrouping<TKey, TNewElement>
{
private readonly IGrouping<TKey, TElement> innerGrouping;
public Grouping(IGrouping<TKey, TElement> innerGrouping )
{
this.innerGrouping = innerGrouping;
}
public TKey Key { get { return innerGrouping.Key; } }
public IEnumerator<TNewElement> GetEnumerator() { return innerGrouping.Cast<TNewElement>().GetEnumerator(); }
IEnumerator IEnumerable.GetEnumerator() { return innerGrouping.GetEnumerator(); }
}
public Lookup(ILookup<TKey, TElement> innerLookup)
{
this.innerLookup = innerLookup;
}
public IEnumerator<IGrouping<TKey, TNewElement>> GetEnumerator()
{
return innerLookup.Select(g => new Grouping(g)).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool Contains(TKey key)
{
return innerLookup.Contains(key);
}
public int Count
{
get { return innerLookup.Count; }
}
public IEnumerable<TNewElement> this[TKey key]
{
get { return innerLookup[key].Cast<TNewElement>(); }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment