Get Max value from List<myType>

Waheed picture Waheed · Aug 12, 2010 · Viewed 196.8k times · Source

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?

Answer

Kobi picture Kobi · Aug 12, 2010

Assuming you have access to LINQ, and Age is an int (you may also try var maxAge - it is more likely to compile):

int maxAge = myTypes.Max(t => t.Age);

If you also need the RandomID (or the whole object), a quick solution is to use MaxBy from MoreLinq

MyType oldest = myTypes.MaxBy(t => t.Age);