C# 实现Sort接口 排序自定义实体类集合

预定义实体类

 class SortClass
        {
            public SortClass(int id,String value)
            {
                this.Id = id;
                this.Value = value;
            }

            String _Value = String.Empty;

            public String Value
            {
                get { return _Value; }
                set { _Value = value; }
            }

            int _Id = 0;

            public int Id
            {
                get { return _Id; }
                set { _Id = value; }
            }
        }

测试方法

        private static void sorttest()
        {
            List sortlist = new List();
            sortlist.Add(new SortClass(5, "v5"));
            sortlist.Add(new SortClass(3, "v3"));
            sortlist.Add(new SortClass(4, "v4"));
            sortlist.Add(new SortClass(5, "v5"));
            sortlist.Add(new SortClass(77, "v77"));
            Console.WriteLine("排序前");
            Console.WriteLine(String.Join("\n", from a in sortlist select String.Format("id:{0}\tvalue:{1}", a.Id, a.Value)));
            Console.WriteLine("排序后");
            sortlist.Sort(SortFunc);
            Console.WriteLine(String.Join("\n", from a in sortlist select String.Format("id:{0}\tvalue:{1}", a.Id, a.Value)));

        }

Sort函数实现

  private static int SortFunc(SortClass x, SortClass y)
        {
            if(x.Id>y.Id)
            {
                return 1;
            }
            else if(x.Id == y.Id)
            {
                return 0;
            }
            return -1;
        }

测试结果
C# 实现Sort接口 排序自定义实体类集合_第1张图片

你可能感兴趣的:(C#)