• 推荐
  • 评论
  • 收藏

C# List<T>.Sort排序

2022-12-07    4683次浏览
定义一个类型

    public class tt
    {
        public int id;
        public string name;
        public string sex;
    }

测试

List<tt> list = new List<tt>();
            for (int i = 5; i > 0; i--)
            {
                tt t = new tt();
                t.id = i;
                t.name = "name" + i;
                t.sex = "sex" + i;
                list.Add(t);
            }

            StringBuilder sb = new StringBuilder();
            foreach (tt t in list)
            {
                sb.AppendLine("{id=" + t.id + ",name=" + t.name + ",sex=" + t.sex + "}");
            }
            MessageBox.Show("排序前\n" + sb.ToString());

            list.Sort(delegate(tt small, tt big) { return small.id - big.id; });

            sb = new StringBuilder();
            foreach (tt t in list)
            {
                sb.AppendLine("{id=" + t.id + ",name=" + t.name + ",sex=" + t.sex + "}");
            }
            MessageBox.Show("排序后\n" + sb.ToString());

原文地址:https://www.cnblogs.com/Leo_wl/p/2088458.html