maxby

Getting the MoreLinq MaxBy function to return more than one element

隐身守侯 提交于 2019-12-25 12:44:29
问题 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

Returning all maximum or minimum values that can be multiple

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-17 10:00:51
问题 Enumerable#max_by and Enumerable#min_by return one of the relevant elements (presumably the first one) when there are multiple max/min elements in the receiver. For example, the following: [1, 2, 3, 5].max_by{|e| e % 3} returns only 2 (or only 5 ). Instead, I want to return all max/min elements and in an array. In the example above, it would be [2, 5] (or [5, 2] ). What is the best way to get this? 回答1: arr = [1, 2, 3, 5] arr.group_by{|a| a % 3} # => {1=>[1], 2=>[2, 5], 0=>[3]} arr.group_by{