首页 > 学院 > 开发设计 > 正文

对集合排序的三种方式

2019-11-17 02:28:02
字体:
来源:转载
供稿:网友

对集合排序的三种方式

对集合排序,可能最先想到的是使用OrderBy方法。

    class PRogram
    {
        static void Main(string[] args)
        {
            IEnumerable<Student> result = GetStudents().OrderBy(r => r.Score);
            foreach (var item in result)
            {
                Console.WriteLine(item.Name + "--" + item.Score);
            }
            Console.ReadKey();
        }
        private static List<Student> GetStudents()
        {
            return new List<Student>()
            {
                new Student(){Id = 1, Name = "张三",Age = 15, Score = 80},
                new Student(){Id = 2, Name = "李四",Age = 16, Score = 70},
                new Student(){Id = 3, Name = "赵武",Age = 14, Score = 90}
            };
        }
    }
    public class Student 
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public int Score { get; set; }
    }

以上,OrderBy返回的类型是IEnumerable<Student>。

如果想使用List<T>的Sort方法,就需要让Student实现IComparable<Student>接口。

   class Program
    {
        static void Main(string[] args)
        {
            List<Student> result = GetStudents();
            result.Sort();
            foreach (var item in result)
            {
                Console.WriteLine(item.Name + "--" + item.Score);
            }
            Console.ReadKey();
        }
        private static List<Student> GetStudents()
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表