Get Max value from List<myType>

Viewed 250948

I have List List<MyType>, my type contains Age and RandomID

Now I want to find the maximum age from this list.

What is the simplest and most efficient way?

8 Answers
var maxAge = list.Max(x => x.Age);

Easiest way is to use System.Linq as previously described

using System.Linq;

public int GetHighestValue(List<MyTypes> list)
{
    return list.Count > 0 ? list.Max(t => t.Age) : 0; //could also return -1
}

This is also possible with a Dictionary

using System.Linq;

public int GetHighestValue(Dictionary<MyTypes, OtherType> obj)
{
    return obj.Count > 0 ? obj.Max(t => t.Key.Age) : 0; //could also return -1
}

Simplest is actually just Age.Max(), you don't need any more code.

Related