日期:2014-05-17 浏览次数:20973 次
using System; using System.Collections.Generic; /// <summary> /// 学生类 /// </summary> public class Student { private string name; // 姓名 public string Name { get { return name; } set { } } private int age; // 年龄 public int Age { get { return age; } set { age = value; } } private string grade; // 年级 public string Grade { get { return grade; } set { grade = value; } } //构造函数 public Student(string name, int age, string grade) { this.name = name; this.age = age; this.grade = grade; } public override string ToString() { return this.name + "," + this.age.ToString() + "," + this.grade; } }
using System; using System.Collections.Generic; public class test { public static void Main() { List<Student> arr = new List<Student>(); arr.Add(new Student("张三", 7, "一年级")); arr.Add(new Student("李四", 11, "二年级")); arr.Add(new Student("王五", 21, "一年级")); arr.Add(new Student("陈六", 8, "三年级")); arr.Add(new Student("刘七", 15, "二年级")); // 调用Sort方法,传入一个匿名方法,实现按年级排序 arr.Sort(delegate(Student x, Student y) { return x.Grade.CompareTo(y.Grade ); }); // 循环显示集合里的元素 foreach( Student item in arr) Console.WriteLine(item.ToString()); // 调用Sort方法,传入一个匿名方法,实现按姓名排序 arr.Sort(delegate(Student x, Student y) { return x.Name.CompareTo(y.Name); }); // 循环显示集合里的元素 foreach( Student item in arr) Console.WriteLine(item.ToString()); } }