c# - Getting a sub set of SortedDictionary as a SortedDictionary -
in c# how filter sorteddictionary using linq producing subset sorteddictionary? eg. i'd write
sorteddictionary<int, person> source = ..fetch.. sorteddictionary<int, person> filtered = source.where(x=>x.foo == bar)
the way i've found create helper method , use that
sorteddictionary<tkey, tvalue> subdictionary<tkey, tvalue> ienumerable<keyvaluepair<tkey, tvalue>> l) { sorteddictionary<tkey, tvalue> result = new sorteddictionary<tkey, tvalue>(); foreach (var e in l) result[e.key] = e.value; return result; } ... sorteddictionary<int, person> source = ..fetch.. sorteddictionary<int, person> filtered = subdictionary(source.where(x=>x.foo == bar))
if want one-statement solution, work:
sorteddictionary<int, person> filtered = new sorteddictionary<int, person>( source.where(x => x.value.foo == bar) .todictionary(kvp => kvp.key, kvp => kvp.value));
however, inefficient, creates 2 dictionary objects (the todictionary() extension method creates one, passed sorteddictionary constructor).
your helper method result in better performance. cleaner syntax, make extension method on ienumerable<keyvaluepair<tkey, tvalue>>:
public static class keyvaluepairenumerableextensions { public static sorteddictionary<tkey, tvalue> tosorteddictionary<tkey, tvalue>( ienumerable<keyvaluepair<tkey, tvalue>> l) { sorteddictionary<tkey, tvalue> result = new sorteddictionary<tkey, tvalue>(); foreach (var e in l) result[e.key] = e.value; return result; } }
which can used this:
var f2 = source.where(x => x.value.foo == bar).tosorteddictionary();
Comments
Post a Comment