tags:

views:

54

answers:

4

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???

Thanks

+2  A: 

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);
Kobi
No, dont have LINQ access....
Waheed
@Waheed - then you should add it to your question. What version are you using - 2.0 or 3.0?
Kobi
Sorry for that. I am using 2.0
Waheed
A: 
thelist.Max(e => e.age);
thelost
A: 
int max = myList.Max(r => r.Age);

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.max.aspx

anishmarokey
+3  A: 

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 = FindMax(list, delegate(MyType x) { return x.Age; });

// C# 3
int maxAge = FindMax(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));
}
Jon Skeet