gpt4 book ai didi

c# - 在 ArrayList c# 中的多个参数之间排序

转载 作者:太空宇宙 更新时间:2023-11-03 19:06:27 26 4
gpt4 key购买 nike

我是 c# 的新手,在作业中卡住了。这个想法是用另一个类的多个参数创建一个 Arraylist。我应该只对列表中的一个参数进行排序。如果只有一个参数没有问题,但我有 5 个。我该怎么办?

ArrayList people = new ArrayList();
people.Add(new Student("Maria", "Svensson", "1989-06-14", "C#Programming", 7));
people.Add(new Student("Bahar", "Nasri", "1992-08-04", "C#Programming", 5));
people.Add(new Student("Kent", "Kaarik", "1967-12-12", "Software Development", 8));
people.Add(new Student("Ahmed", "Khatib", "1990-06-06", "C#Programming", 9));
people.Add(new Student("Lisa", "Lundin", "1984-01-22", "Software Development", 6));
people.Add(new Student("Peter", "Stark", "1987-08-24", "Software Development", 4));
people.Add(new Student("Christer", "Stefansson", "1987-04-02", "C#Programming", 10));

people.Sort();
foreach (Student item in people)
{
Console.WriteLine(item.firstN + " " + item.lastN + " " + item.birthD + " " + item.courseT + " " + item.gradeH);
}

我还收到“无法比较数组中的两个元素”这让我相信我需要 ICompare 命令,但我不确定如何使用它。我究竟做错了什么?感谢您的帮助!!

最佳答案

您必须创建一个 Comparer 类并将其传递给 ArrayList.Sort():

    public class StudentComparer : IComparer<Student>, IComparer
{
public int Compare(Student x, Student y)
{
return x.Name.CompareTo(y.Name);
}


public int Compare(object x, object y)
{
return Compare(x as Student, y as Student);
}
}

然后像这样使用它:

 list.Sort(new StudentComparer());

关于c# - 在 ArrayList c# 中的多个参数之间排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26516965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com