3

我对 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.
*/
4

4 回答 4

2
var pet = pets.OrderByDescending(p => p.Age).First();    

var name = pets.OrderByDescending(p => p.Age).First().Name;

你也可以使用morelinq 的 MaxBy

var name = pets.MaxBy(p=>p.Age).Name;
于 2012-09-09T20:32:09.117 回答
1

另一种解决方案是修改CompareTo()方法:

int IComparable<Pet>.CompareTo(Pet pet)
{
    return this.Age.CompareTo( pet.Age );
}

然后:

var olderPet = pets.Max(); 
Console.WriteLine(olderPet.Name);   

编辑1:

我如何从两个列表中获取姓名和年龄?列表名称 = 新列表();列表年龄=新列表();是我有信息的地方。

如果我理解您需要从给定的两个列表中创建另一个宠物列表。因此,您必须将其添加到Pet类中:

public Pet(string Name, int Age){
    this.Name = Name;
    this.Age = Age;
}

然后执行此操作以从两个列表中创建 Pets 列表:

List<Pet> listPets = new List<Pet>();
for(int i = 0; i < listNames.Count; i++){
    listPets.Add(new Pet(name[i], age[i]));
}

请记住,这两个列表必须具有相同的长度,否则此代码将抛出ArgumentOutOfRangeException.

编辑2:

然而,当我把它们放在一起时,我得到了“Pet.Pet”的输出。如何粘贴代码以显示?

如果要打印新列表的所有内容,可以执行以下操作:

foreach(Pet pet in listPets)
  Console.WriteLine("Name: " + pet.Name + "," + "Age: " + pet.Age.ToString());

或者您可以将其添加到您的宠物类中:

public override string ToString(){
   return "Name: " + Name + "," + "Age: " + Age.ToString();
}

然后使用此代码打印列表的所有内容:

foreach(Pet pet in listPets)
  Console.WriteLine(pet.ToString());
于 2012-09-09T20:48:37.150 回答
0

我很困惑。你问“我如何得到对应的名字?” 并且您的代码返回正确答案。然后你问“有没有办法从列表中创建新对象?” 答案是肯定的,但你到底想通过这样做来归档什么?

如果你想找到最老的宠物,你的 CompareTo 方法是不正确的。它应该如下所示:

public int IComparable<Pet>.CompareTo(Pet other)
{
    return this.Age - other.Age;
}
于 2012-09-09T20:42:09.957 回答
0

您可以使用 Zip 迭代这两个列表:

var pets = names.Zip(ages, (n, a) => new Pet { Name = n, Age = a });

然后你可以使用 Max 根据你的比较函数得到最大值:

var maxPet = pers.Max();
于 2012-09-10T11:55:45.443 回答