从List< myType>获取最大值
问题描述:
我有列表List<MyType>
,我的类型包含Age
和RandomID
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?
答
好的,因此,如果您没有LINQ,则可以对其进行硬编码:
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;
}
您可以将其用于:
// C# 2
int maxAge = FindMaxValue(list, delegate(MyType x) { return x.Age; });
// C# 3
int maxAge = FindMaxValue(list, x => x.Age);
或者您可以使用 LINQBridge :)
在每种情况下,如果需要,都可以通过简单调用Math.Max
来返回if块.例如:
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));
}