How to Perform .Max() on a Property of All Objects in a Collection and Return the Object With Maximum Value

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

We have an extension method to do exactly this in MoreLINQ. You can look at the implementation there, but basically it's a case of iterating through the data, remembering the maximum element we've seen so far and the maximum value it produced under the projection.

In your case you'd do something like:

var item = items.MaxBy(x => x.Height);

This is better (IMO) than any of the solutions presented here other than Mehrdad's second solution (which is basically the same as MaxBy):

  • It's O(n) unlike the previous accepted answer which finds the maximum value on every iteration (making it O(n^2))
  • The ordering solution is O(n log n)
  • Taking the Max value and then finding the first element with that value is O(n), but iterates over the sequence twice. Where possible, you should use LINQ in a single-pass fashion.
  • It's a lot simpler to read and understand than the aggregate version, and only evaluates the projection once per element

How to get the max value of a function in a list of objects (C#) ? -Beginner-

You need to use maximumArea to store the max of the list, not the max of the current pair.

Trapezoid maximumArea = new Square(0);  //Smallest possible trapezoid

foreach (Trapezoid t in Shape)
{
if (t.Area() > maximumArea.Area()) maximumArea = t;
}
Console.WriteLine(maximumArea);

You can also shorten this considerably using LINQ:

var maximumArea = shape.OrderByDescending( x => x.Area() ).First();

And if there's a chance that some trapezoids will tie, maybe you should get a list:

var max = shape.Max( x => x.Area() );
var maximumAreas = shape.Where( x => x.Area() == max).ToList();

C# Using LINQ to filter each Object with Max Value in List of Objects

You can achieve the desired result at once with a simple GroupBy and subsequent ordering within each group:

var highestByTitle = list
.GroupBy(t => t.title)
.Select(g => g.OrderByDescending(t => t.val).First())
.ToList();

Demo.

How to get Max from List CustomType and return whole type not only number?

Another option is using list.Max() only and implement IComparable<Custom>, so your class would be:

public class Custom : IComparable<Custom>
{
public int Id { get; set; }
public OtherCustom OtherCustom { get; set; }
public Custom(int id, OtherCustom otherCustom)
{
Id = id;
OtherCustom = otherCustom;
}

public int CompareTo([AllowNull] Custom other)
{
return Id.CompareTo(other.Id);
}
}

And your max would pretty simple

Custom custom1 = new Custom(1, new OtherCustom());
Custom custom2 = new Custom(2, new OtherCustom());
Custom custom3 = new Custom(3, new OtherCustom());
Custom custom4 = new Custom(1, new OtherCustom());
List<Custom> list = new List<Custom>();
list.Add(custom1);
list.Add(custom2);
list.Add(custom3);
list.Add(custom4);

var item = list.Max();

Return object with highest value

You can do a simple one-line reduce:

let maxGame = games.reduce((max, game) => max.votes > game.votes ? max : game);

Note: You should make sure games is not empty before you hit this code. As pointed out in the comments, this code will throw an error if games is empty.

(You could instead provide an initial value to .reduce to avoid the error. But it'll usually be most straightforward to check whether games is empty to begin with, rather than provide a dummy/default value and then later checking whether you got that dummy/default value.)

Get from a List t the record with the maximum value of a specific property

You can OrderByDescending the List<Product> on the ActivationDate Field and then take FirstOrDefault()

Product.OrderByDescending(p => p.ActivationDate).FirstOrDefault();

For a more simpler version there is an extension method

MaxBy

Product.MaxBy(p => p.ActivationDate);

Finding the max value of an attribute in an array of objects

To find the maximum y value of the objects in array:

    Math.max.apply(Math, array.map(function(o) { return o.y; }))

or in more modern JavaScript:

    Math.max(...array.map(o => o.y))

How to force max to return ALL maximum values in a Java Stream?

I would group by value and store the values into a TreeMap in order to have my values sorted, then I would get the max value by getting the last entry as next:

Stream.of(1, 3, 5, 3, 2, 3, 5)
.collect(groupingBy(Function.identity(), TreeMap::new, toList()))
.lastEntry()
.getValue()
.forEach(System.out::println);

Output:

5
5

Getting max value from an arraylist of objects?

Use a Comparator with Collections.max() to let it know which is greater in comparison.


Also See

  • How to use custom Comparator


Related Topics



Leave a reply



Submit