根据对象值之一对对象类型的数组进行排序

发布于 2024-09-27 01:44:40 字数 208 浏览 1 评论 0原文

我有一个名为学生的班级,该班级有两个元素(姓名,ID)。 在我的主课中,我在一个数组中创建了大约 10 个学生,我称之为学生,

现在我想根据 ID 或名称对学生数组进行排序!

如果我使用这行代码,

array.sort(students);

有没有办法使用排序方法并选择我想要对数组进行排序的元素???

i have a class called student, the class have two elements (Name, ID).
in my main class, i have created about 10 students in an array i called it students,

now i want to sort the the students array respecting the ID, or the name!!

if i used this line of code

array.sort(students);

is there a way to use the sort method and choose which element i want to sort the array with???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

So要识趣 2024-10-04 01:44:40

您可以使用这样的东西:

Array.Sort(array, (s1, s2) => s1.Name.CompareTo(s2.Name));

您可以定义比较器函数,但是您想要获得不同的排序顺序。

You could use something like this:

Array.Sort(array, (s1, s2) => s1.Name.CompareTo(s2.Name));

You can define the comparator function however you want to get different sorting orders.

紙鸢 2024-10-04 01:44:40

我会为此使用一个列表。

List<Student> students = new List<Student>{ new Student(), new Student(), new Student() }

然后使用 LINQ 对该列表进行排序

var sortedStuds = students.OrderBy(s => s.ID).ToList();

,其中 sStudent 对象

I would use a list for this.

List<Student> students = new List<Student>{ new Student(), new Student(), new Student() }

then sort that list with LINQ

var sortedStuds = students.OrderBy(s => s.ID).ToList();

where the s is a Student object

恏ㄋ傷疤忘ㄋ疼 2024-10-04 01:44:40

如果是数组,最有效的方法是使用 Array.Sort:

Array.Sort(array, (s1, s2) => s1.Name.CompareTo(s2.Name));

If it’s an array, the most efficient way is to use Array.Sort:

Array.Sort(array, (s1, s2) => s1.Name.CompareTo(s2.Name));
忘你却要生生世世 2024-10-04 01:44:40

你可以使用 linq:

sortedStudents1 = students.OrderBy(s=>s.Name).ToList();
sortedStudents2 = students.OrderBy(s=>s.ID).ToList();

you can use linq:

sortedStudents1 = students.OrderBy(s=>s.Name).ToList();
sortedStudents2 = students.OrderBy(s=>s.ID).ToList();
偏爱你一生 2024-10-04 01:44:40

虽然我也更喜欢 LINQ 解决方案,但您也可以让您的 Student 类实现 IComparable,这可以为您提供更复杂的排序选项,而不必每次都编写内联函数。

While I also prefer the LINQ solution, you could alternatively make your Student class implement IComparable, which could give you more complex sorting options without having to write an in-line function every time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文