c# - How to get multiple most commons values from array and add them to another? -
i have array this:
[2 1 2 4 3 3 1]
i'm using this...
var query = array.groupby(item => item) .orderbydescending(g => g.count()) .select(g => g.key) .first();
.. first common value (in case : 2)
what if want multiple values (in case: 2,3,1) ?
i need add values temporary array check if temparray.count > 1.
if groups tied top count, this:
var tmp = array .groupby(item => item) .orderbydescending(g => g.count()) .select(g => new { item = g.key , count = g.count() }).tolist(); var res = tmp .takewhile(p => p.count == tmp[0].count) .select(p => p.item) .tolist();
note check tmp
list count non-zero unnecessary, because way takewhile
condition executed when there @ least single item in temporary list. in other words, when tmp
empty, lambda condition p => p.count == tmp[0].count
never reached, , out-of-range exception never thrown.
Comments
Post a Comment