List .Sort() 排序的用法


List<T> 可以通過 .Sort()進行排序,但是當 T 對象為自定義類型時(比如自定義模型),就需要 IComparable接口重寫其中的方法來實現,實現代碼如下:

class Program
    {
        static Func<Model, int> where = a => a.id;
        static Func<Model, bool> wherelambda = a => a.id < 3;
        static void Main(string[] a)
        {
            List<Model> result = GetData().ToList();
            result.Sort();          //排序
        } 

        /// <summary>
        /// 拼裝數據
        /// </summary>
        /// <returns></returns>
        #region  
        public static IList<Model> GetData()
        {
            IList<Model> list = new List<Model>();
            for (int i = 0; i <= 10; i++)
            {
                Model model = new Model();
                model.id = i;
                model.Name = "名字" + i;
                model.Email = string.Format("12345@QQ{0}.com.cn", i);
                list.Add(model);
            }
            return list;
        }
        #endregion
    }

    /// <summary>
    /// 自定義模型 一定要繼承 IComparable<T>接口
    /// </summary>
    public class Model : IComparable<Model>
    {
        public int id { get; set; }

        private int Sex { get; set; }

        public string Name { get; set; }

        public DateTime? BirthDate { get; set; }

        public string Email { get; set; }

        public string Phone { get; set; }

        public int CompareTo(Model model)
        {
            if (model.id == id && model.Name.Equals(Name))
                return 0;
            else
            {
                if (id > model.id)
                {
                    return -1;
                }
                if (Name.CompareTo(model.Name) > 0)
                {
                    return -1;
                }
                else
                    return 1;
            }

        }
    }

如果不繼續IComparable接口,也可以直接在 .Sort()方法里面寫,代碼如下:

class Program
    {
        static Func<Model, int> where = a => a.id;
        static Func<Model, bool> wherelambda = a => a.id < 3;
        static void Main(string[] a)
        {
            List<Model> result = GetData().ToList();
            result.Sort((a,b)=>{
                if (b.id == a.id && b.Name.Equals(a.Name))
                    return 0;
                else
                {
                    if (a.id > b.id)
                    {
                        return -1;
                    }
                    if (a.Name.CompareTo(b.Name) > 0)
                    {
                        return -1;
                    }
                    else
                        return 1;
                }
            });          //排序
        } 

 按照功能排序:List<T> < IList<T> < ICollection<T> < IEnumerable<T>

按照性能排序:IEnumerable<T> < ICollection<T> < IList<T> < List<T>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM