Search code examples
linqmaxbymorelinq

Getting the MoreLinq MaxBy function to return more than one element


I have a situation in which I have a list of objects with an int property and I need to retrieve the 3 objects with the highest value for that property. The MoreLinq MaxBy function is very convenient to find the single highest, but is there a way I can use that to find the 3 highest? (Not necessarily of the same value). The implementation I'm currently using is to find the single highest with MaxBy, remove that object from the list and call MaxBy again, etc. and then add the objects back into the list once I've found the 3 highest. Just thinking about this implementation makes me cringe and I'd really like to find a better way.


Solution

  • in this case, you could simply do

    yourResult.OrderByDescending(m => m.YourIntProperty)
    .Take(3);
    

    Now, this will retrieve you 3 objects.

    So if you've got 4 objects sharing the same value (which is the max), 1 will be skipped. Not sure if that's what you want, or if it's not a problem...

    But MaxBy will also retrieve only one element if you have many elements with the same "max value".