c# - How do I get the Nth largest element from a list with duplicates, using LINQ? -


i've seen in various stackoverflow answers can nth largest element in list doing

var nthfromtop = items.orderbydescending().skip(n-1).first(); 

but wouldn't work if there no duplicates in list? if list contains duplicates, there way nth largest element (or set of elements) using linq? if not, efficient way in c#?

to set of items equal nth largest item you'll need group items, order groups, , decrement n group size while n positive. when n reaches zero, you've hit group containing nth largest item.

public static ienumerable<t> foo<t>(this ienumerable<t> source, int n) {     return source.groupby(x => x)         .orderbydescending(group => group.key)         .skipwhile(group =>         {             n -= group.count();             return n > 0;         })         .first(); } 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -