You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用选择排序按三个指定属性对学生类列表排序

学生类多属性选择排序实现方案

现有代码问题梳理

  • 方法内新实例化的AllYearStudents是空对象,完全没有用到传入的学生集合,没有排序数据源
  • 直接用<比较两个学生对象,C#默认不支持自定义类的比较运算符,需要自行实现多属性比较逻辑
  • 找到最小元素下标后没有执行交换元素的逻辑,排序流程不完整
  • 缺少多优先级排序规则,没有按照出生日期、姓氏、名字的顺序做分级比较

实现代码

首先确认你的学生类可访问对应属性,示例定义如下:

public class Student
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public DateTime Birthdate { get; set; }
    public int Id { get; set; }
    public string Course { get; set; }
    public string PhoneNumber { get; set; }
}

修改后的排序方法如下(和你原有StudentsRegister的API逻辑对齐):

public void SortStudents(StudentsRegister students)
{
    int count = students.StudentsCount();
    // 选择排序外层循环
    for (int i = 0; i < count - 1; i++)
    {
        int minIndex = i;
        // 内层循环查找最小元素下标
        for (int j = i + 1; j < count; j++)
        {
            Student current = students.Get(j);
            Student currentMin = students.Get(minIndex);
            bool isCurrentSmaller = false;
            
            // 第一优先级:比较出生日期,更早的排前面
            if (current.Birthdate < currentMin.Birthdate)
            {
                isCurrentSmaller = true;
            }
            // 出生日期相同,第二优先级:比较姓氏,按字典序升序
            else if (current.Birthdate == currentMin.Birthdate)
            {
                int lastNameRes = string.Compare(current.LastName, currentMin.LastName);
                if (lastNameRes < 0)
                {
                    isCurrentSmaller = true;
                }
                // 姓氏也相同,第三优先级:比较名字,按字典序升序
                else if (lastNameRes == 0)
                {
                    int firstNameRes = string.Compare(current.FirstName, currentMin.FirstName);
                    if (firstNameRes < 0)
                    {
                        isCurrentSmaller = true;
                    }
                }
            }

            if (isCurrentSmaller)
            {
                minIndex = j;
            }
        }
        // 交换最小元素和当前位置元素
        if (minIndex != i)
        {
            Student temp = students.Get(i);
            students.Set(i, students.Get(minIndex));
            students.Set(minIndex, temp);
            // 若StudentsRegister已实现Swap方法可直接替换为 students.Swap(i, minIndex)
        }
    }
}

核心逻辑说明

选择排序的核心逻辑和数字数组排序完全一致,仅把数字的大小比较替换成了自定义的多属性分级比较规则:前一个属性值相等时才会进入下一个属性的比较,严格匹配你要求的排序优先级。

内容的提问来源于stack exchange,提问作者rokenga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 01:24:03