Home > Software design >  LINQ Select in descending order from collection, three different values that go up to the maximum va
LINQ Select in descending order from collection, three different values that go up to the maximum va

Time:11-12

For example i have a collection like this

var c1 = new Collection<int>{0,0,2,2,2,3,3,4,4,4,4,5,5,6,6,7};  

I would like to get result like this

(6,5,4)

CodePudding user response:

You can do:

c1.Distinct()
    .OrderByDescending(x => x)
    .Skip(1)
    .Take(3)
    .ToList()

First remove all the duplicates, then sort despondingly. Skip(1) so that the max element is removed. Finally you can take 3 elements from the rest.

CodePudding user response:

In the old days, before LINQ, we might have done this on a sorted collection like you have:

var maxes = new int[4];
var idx = 0;
var max = 0;
foreach(var c in c1)
  if(c > max)
    max = maxes[(idx  )%4] = c;

At the end of this you'll have an array with 4 max values - the 3 you want, and the one you don't (which is in (idx - 1) % 4). I don't know if I'd use it now, but it's more efficient than a "distinct, then sort, then skip then take" approach as it does its work in a single pass

  • Related