Obtener el valor máximo de la Lista


Tengo Lista List<MyType>, mi tipo contiene Age y RandomID

Ahora quiero encontrar la edad máxima de esta lista.

¿Cuál es la forma más sencilla y eficiente?

 35
Author: Arulkumar, 2010-08-12

6 answers

Está bien, así que si no tienes LINQ, puedes codificarlo:

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;
}

O podría escribir una versión más general, reutilizable en muchos tipos de listas:

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;
}

Puedes usar esto con:

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

// C# 3
int maxAge = FindMax(list, x => x.Age);

O podrías usar LINQBridge :)

En cada caso, puede devolver el bloque if con una simple llamada a Math.Max si lo desea. Por ejemplo:

foreach (T item in list)
{
    maxValue = Math.Max(maxValue, projection(item));
}
 26
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-12 05:28:06

Asumiendo que tienes acceso a LINQ, y Age es un int (también puedes probar var maxAge - es más probable que compile):

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

Si también necesita el RandomID (o el objeto completo), una solución rápida es usar MaxBy de MoreLinq

MyType oldest = myTypes.MaxBy(t => t.Age);
 71
Author: Kobi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-12 05:21:13
 29
Author: anishMarokey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-12 05:22:29
thelist.Max(e => e.age);
 7
Author: thelost,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-12 05:21:21

¿Qué tal de esta manera:

List<int> myList = new List<int>(){1, 2, 3, 4}; //or any other type
myList.Sort();
int greatestValue = myList[ myList.Count - 1 ];

Básicamente dejas que el método Sort() haga el trabajo por ti en lugar de escribir tu propio método. A menos que no quieras ordenar tu colección.

 0
Author: Behnam Rasooli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-20 03:19:16
var maxAge = list.Max(x => x.Age);
 0
Author: hamid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-20 17:49:28