您的位置:首页 > 编程语言 > C#

c# 接口IComparer<T>

2014-08-20 23:14 337 查看
Sort()方法是集合中默认的排序方法,它的排序方式可以通过IComparable接口实现。

如果要指定排序方式可以实现IComparer接口的Compare(T x,T y)方法Sort(Icomparer)

降序,升序年龄比较器

 class AgeDesc : IComparer<Student> {

        #region IComparer<Student> 成员

        public int Compare(Student x, Student y)

        {

            return y.Age.CompareTo(x.Age);

        }

        #endregion

    }

    class AgeAsc : IComparer<Student> {

        #region IComparer<Student> 成员

        public int Compare(Student x, Student y)

        {

            return x.Age.CompareTo(y.Age);

        }

        #endregion

    }

 private void btnAgeDesc_Click(object sender, EventArgs e)

        {

            student.Sort(new AgeDesc());

            Print(student);

        }

        private void Print(List<Student> stu) {

            this.listView1.Items.Clear();

            foreach (Student st in stu) {

                ListViewItem lvi = new ListViewItem(st.Name);

                lvi.SubItems.AddRange(new string[] {st.Age.ToString()});

                listView1.Items.Add(lvi);

            }

        }

        private void btnAgeAsc_Click(object sender, EventArgs e)

        {

            student.Sort(new AgeAsc());

            Print(student);

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  List Sort 排序