在ArrayList c#中的多个参数之间排序
本文关键字:参数 之间 排序 ArrayList | 更新日期: 2023-09-27 18:27:26
我是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());
IMHO,您应该接受切换到List而不是旧的非通用ArrayList的建议。如果你这样做,那么对列表进行排序就很简单:
people.Sort((s1, s2) => s1.Name.CompareTo(s2.Name));
如果你想坚持使用ArrayList,它几乎很简单:
people.Sort(Comparer<Student>.Create((s1, s2) => s1.Name.CompareTo(s2.Name)));
考虑一个泛型列表list而不是Arraylist。然后使用LINQ对列表进行排序。
List<Student> people = new List<Student>();
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));
var orderedPeople = people.OrderBy(x => x.lastN);
foreach (Student item in orderedPeople)
{
Console.WriteLine(item.firstN + " " + item.lastN + " " + item.birthD + " " + item.courseT + " " + item.gradeH);
}
要按多列排序,请使用ThenBy。
var orderedPeople = people.OrderBy(x => x.lastN).ThenBy(x => x.firstN);
感谢您的建议。我最后做了一个通用列表列表,最后一切都很顺利。对于这个任务,我本应该用ArrayList做一个,但最终通用的似乎要好得多。我希望一切都会好起来!