我有一个列表 List<MyType>
,其中 MyType 包含 Age
和 RandomID
现在我想从这个列表中找到最大的年龄。
最简单和最有效的方法是什么?
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;
}
或者您可以编写一个更通用的版本,可在许多列表类型中重复使用:
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块。例如:
foreach (T item in list)
{
maxValue = Math.Max(maxValue, projection(item));
}
int max = myList.Max(r => r.Age);
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.max.aspx
var maxAge = list.Max(x => x.Age);
thelist.Max(e => e.age);
最简单的方法是使用先前描述的 System.Linq
using System.Linq;
public int GetHighestValue(List<MyTypes> list)
{
return list.Count > 0 ? list.Max(t => t.Age) : 0; //could also return -1
}
使用字典也可以实现这一点。
using System.Linq;
public int GetHighestValue(Dictionary<MyTypes, OtherType> obj)
{
return obj.Count > 0 ? obj.Max(t => t.Key.Age) : 0; //could also return -1
}
Age.Max()
,不需要任何其他代码。List<int> myList = new List<int>(){1, 2, 3, 4}; //or any other type
myList.Sort();
int greatestValue = myList[ myList.Count - 1 ];
Sort()
方法为你完成工作,而不是编写自己的方法。除非你不想对集合进行排序。List<int>(){ 5, 10, 15, 20 }
,无论何时我们对这个集合进行排序,数字20总是在最后一个索引处,除非我们按降序排序。 - Behnam Rasooli