美文网首页
简单变量在集合中的排序

简单变量在集合中的排序

作者: lianzhanshu | 来源:发表于2017-05-31 21:47 被阅读0次
    • 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();
            }
        }
    }
    
    结果

    相关文章

      网友评论

          本文标题:简单变量在集合中的排序

          本文链接:https://www.haomeiwen.com/subject/kvgjfxtx.html