泛型的排序有3种方法,分别是:
1、List
2、List
3、List
这里介绍第二种方法:
首先定义一个类,用作集合的元素
using System;
using System.Collections.Generic;
///
/// 学生类
///
public class Student
{
private string name;
// 姓名
public string Name
{
get { return name; }
set { name = value; }
}
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
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());
}
}