简单变量在集合中的排序

  • String类型输出排序
namespace DemoDM
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> stuList = new List<string>() { "王勇", "李超", "高新", "赵芳", "雯雯" };
            foreach(string item in stuList)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine("-------排序后输出结果-------");
            stuList.Sort();
            foreach(string item in stuList)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
    }
}
排序
  • 引用类型输出排序
    新建Student类及接口
namespace DemoDM
{
    class Student:IComparable<Student>
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }
        public int StudentAge { get; set; }

        public int CompareTo(Student other)
        {
            return other.StudentAge - this.StudentAge;//按照年龄降序
        }
    }
}

排序输出

namespace DemoDM
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Student> stuList = new List<Student>()
            {
                new Student() { StudentAge = 22, StudentId = 1001, StudentName = "小王" },
                new Student() { StudentAge = 23, StudentId = 1002, StudentName = "小李" },
                new Student() { StudentAge = 32, StudentId = 1003, StudentName = "小朱" },
                new Student() { StudentAge = 29, StudentId = 1004, StudentName = "厉雯" },
                new Student() { StudentAge = 21, StudentId = 1005, StudentName = "小孙" },
            };
            foreach (Student item in stuList)
            {
                Console.WriteLine(item.StudentAge + "\t" + item.StudentId + "\t" + item.StudentName);
            }
            Console.WriteLine("-------排序后输出结果-------");
            stuList.Sort();
            foreach (Student item in stuList)
            {
                Console.WriteLine(item.StudentAge + "\t" + item.StudentId + "\t" + item.StudentName);
            }
            Console.ReadLine();
        }
    }
}
结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容