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.
相关问题
- Check if tie in count of lists using linq
- Trouble with OR in Sharepoint CAML
- get key value pairs from xml using linq
- query and create objects with a one to many relati
- select column from dataset using LINQ
相关文章
- 想问问Linq中有没有根据条件选择要不要关联表。
- Why do I need a ToList() to avoid disposed context
- LINQ .Include() properties from sub-types in TPH i
- Can a method chain be called LINQ?
- Get grouped comma separated values with linq
- How does a LINQ expression know that Where() comes
-
Creating dynamic Expression
> - Entity Framework - An item with the same key has a
in this case, you could simply do
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".Update: In version 3,
MaxBy
(includingMinBy
) of MoreLINQ was changed to return a sequence as opposed to a single item.Use MoreLINQ's
PartialSort
orPartialSortBy
. The example below usesPartialSortBy
to find and print the longest 5 words in a given text:It will print: