我对 C# 比较陌生。
我正在尝试从姓名和年龄列表中查找最大年龄的名称。与下面的示例不同,我不知道提前给出了哪些名字或哪些年龄。
姓名和年龄是从下面的两个列表中创建的。
List<string> name = new List<string>();
List<double> age = new List<double>();
我知道如何使用 Max() 方法找到最大年龄,但如何获得相应的名称?通过下面的示例,是否可以从列表中创建新对象?
/// This class implements IComparable to be able to
/// compare one Pet to another Pet.
/// </summary>
class Pet : IComparable<Pet>
{
public string Name { get; set; }
public int Age { get; set; }
/// <summary>
/// Compares this Pet to another Pet by
/// summing each Pet's age and name length.
/// </summary>
/// <param name="other">The Pet to compare this Pet to.</param>
/// <returns>-1 if this Pet is 'less' than the other Pet,
/// 0 if they are equal,
/// or 1 if this Pet is 'greater' than the other Pet.</returns>
int IComparable<Pet>.CompareTo(Pet other)
{
int sumOther = other.Age + other.Name.Length;
int sumThis = this.Age + this.Name.Length;
if (sumOther > sumThis)
return -1;
else if (sumOther == sumThis)
return 0;
else
return 1;
}
}
public static void MaxEx3()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
Pet max = pets.Max();
Console.WriteLine(
"The 'maximum' animal is {0}.",
max.Name);
}
/*
This code produces the following output:
The 'maximum' animal is Barley.
*/