C# list 排序

using System.Collections.Generic;
using System.Linq;

namespace DailyCoding.Code
{
    public class _20210603_1
    {
        public void Run()
        {
            /*
             * Sort 方法对本集合根据指定的比较器进行排序
             */
            List<_20210603_1_Model> sortList = new List<_20210603_1_Model>();
            sortList.Add(new _20210603_1_Model { Age = 22, Money = 33.13, Name = "N2" });
            sortList.Add(new _20210603_1_Model { Age = 33, Money = 33.19, Name = "N3" });
            sortList.Add(new _20210603_1_Model { Age = 11, Money = 33.12, Name = "N1" });
            sortList.Sort((x, y) =>
            {
                // 根据 Money 降序排序
                if (x.Money > y.Money)
                    return -1; // 升序返回 1;降序返回 -1 ;
                else if (x.Money == y.Money)
                    return 0;
                else
                    return 1; // 升序返回 1;降序返回 -1 ;
            });


            /*
             * OrderBy/OrderByDescending 方法对原集合无影响,返回新的有序集合
             */
            var newList = sortList.OrderBy(t => t.Age); // 根据Age升序排序
            newList = sortList.OrderByDescending(t => t.Money); // 根据Money降序排序
        }
    }

    public class _20210603_1_Model
    {
        public int Age { get; set; }
        public double Money { get; set; }
        public string Name { get; set; }
    }
}

 

posted @ 2021-06-03 09:50  温故纳新  阅读(439)  评论(0编辑  收藏  举报