c# - max per item within list of items -
i have class c has list[b] , each b has dictionary[a, double]
i need select max(double) per i'm doing:
dictionary<a,double> rtn = new dictionary<a,double>(); foreach (var b in c.bs) { foreach (var kvpa in b.a_list.where(a => !rtn.keys.tolist().contains(a))) { rtn.add(kvpa.key, kvpa.value); } foreach(var kvpa in b.a_list.where(a => rtn.keys.contains(a) && a.value>rtn[a])) { rtn[kvpa.key] = kvpa.value; } } homecoming rtn;
however looks messy i'm trying build improve linq query can't figure out syntax. help?
i'll assume max(int) meant "max", in maximum double per unique accross a_lists
, appear dictionaries.
anyway, can in 3 steps in single linq statement:
collapse key value pairs using selectmany group unique using groupby take max double per key using todictionarywhere c
instance of class c
:
var dct = c.bs.selectmany(x => x.a_list) .groupby(p => p.key, p => p.value) .todictionary(g => g.key, g => g.max());
you utilize tolookup in place of todictionary, yield ienumerable iterator on same [a, double]
tuples materialized todictionary.
c# linq
No comments:
Post a Comment