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?
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));
}
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);
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
int max = myList.Max(r => r.Age);
Http://msdn.microsoft.com/en-us/library/system.linq.enumerable.max.aspx
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);
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.
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);
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