Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Max value from List<myType>

Tags:

list

c#-2.0

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?

like image 900
Waheed Avatar asked Aug 12 '10 05:08

Waheed


People also ask

How to get Max value in list c#?

You can use this with: // C# 2 int maxAge = FindMaxValue(list, delegate(MyType x) { return x. Age; }); // C# 3 int maxAge = FindMaxValue(list, x => x. Age);

How to find min value from list in c#?

To get the smallest element, use the Min() method. list. AsQueryable(). Min();

How do I find the max of a list in R?

How to get the max value in a list in R? First, use the unlist() function to convert the list into a vector, and then use the max() function to get the maximum value. The following are the arguments that you can give to the max() function in R. x – The vector for which you want to compute the max value.


2 Answers

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); 
like image 52
Kobi Avatar answered Sep 19 '22 10:09

Kobi


Okay, so if you don't have LINQ, you could hard-code it:

public int FindMaxAge(List<MyType> list) {     if (list.Count == 0)     {         throw new InvalidOperationException("Empty list");     }     int maxAge = int.MinValue;     foreach (MyType type in list)     {         if (type.Age > maxAge)         {             maxAge = type.Age;         }     }     return maxAge; } 

Or you could write a more general version, reusable across lots of list types:

public int FindMaxValue<T>(List<T> list, Converter<T, int> projection) {     if (list.Count == 0)     {         throw new InvalidOperationException("Empty list");     }     int maxValue = int.MinValue;     foreach (T item in list)     {         int value = projection(item);         if (value > maxValue)         {             maxValue = value;         }     }     return maxValue; } 

You can use this with:

// C# 2 int maxAge = FindMaxValue(list, delegate(MyType x) { return x.Age; });  // C# 3 int maxAge = FindMaxValue(list, x => x.Age); 

Or you could use LINQBridge :)

In each case, you can return the if block with a simple call to Math.Max if you want. For example:

foreach (T item in list) {     maxValue = Math.Max(maxValue, projection(item)); } 
like image 30
Jon Skeet Avatar answered Sep 18 '22 10:09

Jon Skeet