c# - Create ILookup<int,int> from IDictionary<int,IEnumerable<int>> -


is there elegant way how transform

idictionary<int, ienumerable<int>> ilookup<int,int> ? far know should identical, find lookups more clear.

story behind more complex i'm forced select list of ids lists of related ids:

masters     .select(m => new {masterid = m.id, childids = m.children.select(c => c.id)})     .todictionary(k => masterid, v => v.childids) 

i happy select directly lookup don't know if possible.

example of master variable type can simple this:

public class master {      public int id { get; set; }      public list<master> children { get; set; } } 

as lasse v. karlsen suggested in comments, create wrapper type exposes ilookup:

public class lookupdictionary<tkey, telement> : ilookup<tkey, telement> {     private readonly idictionary<tkey, ienumerable<telement>> _dic;      public lookupdictionary(idictionary<tkey, ienumerable<telement>> dic)     {         _dic = dic;     }      public int count     {         { return _dic.values.sum(x => x.count()); }     }      public ienumerable<telement> this[tkey key]     {         { return _dic.containskey(key) ? _dic[key] : enumerable.empty<telement>(); }     }      public bool contains(tkey key)     {         return _dic.containskey(key);     }      public ienumerator<igrouping<tkey, telement>> getenumerator()     {         return _dic.select(kv => new lookupdictionarygrouping(kv)).getenumerator();     }      ienumerator ienumerable.getenumerator()     {         return getenumerator();     }      class lookupdictionarygrouping : igrouping<tkey, telement>     {         private keyvaluepair<tkey, ienumerable<telement>> _kvp;          public tkey key         {             { return _kvp.key; }         }          public ienumerator<telement> getenumerator()         {             return _kvp.value.getenumerator();         }          ienumerator ienumerable.getenumerator()         {             return getenumerator();         }          public lookupdictionarygrouping(keyvaluepair<tkey, ienumerable<telement>> kvp)         {             _kvp = kvp;         }     } } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -