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
Post a Comment