利用List的Sort()、Find()、FindAll()、Exist()来解决一些问题
最近写案子常常用到List<T>,这个东西还真好用
因为它有下列东西:
List<T>.Sort() → 排序T
List<T>.Find() → 找出一个T
List<T>.FindAll() →找出多个T
List<T>.Exist() →判断T是否存在
小弟就写个范例介绍这些东西吧..
List<Person> lstPerson = new List<Person>();
lstPerson.Add(new Person(1, "puma", 10));
lstPerson.Add(new Person(2, "F6 Team", 20));
lstPerson.Add(new Person(3, "ASP.NET", 30));
lstPerson.Add(new Person(4, "Dotblogs", 40));
//原始资料显示在GridView上
this.GridView1.DataSource = lstPerson;
this.GridView1.DataBind();
//List<T>.Find()
//找出Name='puma'的Person
Response.Write("找出Name='puma'的Person→ ");
Response.Write(lstPerson.Find(delegate(Person p) { return p.Name == "puma"; }).ToString();
//List<T>.FindAll()
//找出Age>10的数目
Response.Write("找出Age>10的数目→ ");
Response.Write(lstPerson.FindAll(delegate(Person p) { return p.Age > 10; }).Count.ToString();
//List<T>.Exists()
//检查Name='F6'是否存在
Response.Write("检查Name='F6'是否存在→ ");
Response.Write(lstPerson.Exists(delegate(Person p) { return p.Name == "F6"; }).ToString();
//List<T>.Sort()
//依Name升幂排序
Response.Write("<p>依Name升幂排序↑<br/>");
lstPerson.Sort(delegate(Person p1, Person p2) { return Comparer<string>.Default.Compare(p1.Name, p2.Name); });
foreach (Person p in lstPerson)
Response.Write(p.ToString() + "<br/>");
//List<T>.Sort()
//依Name降幂排序
Response.Write("<p>依Name降幂排序↓<br/>");
lstPerson.Sort(delegate(Person p1, Person p2) { return Comparer<string>.Default.Compare(p2.Name, p1.Name); });
foreach (Person p in lstPerson)
Response.Write(p.ToString() + "<br/>");
ublic class Person
private int _ID;
private string _Name;
private int _Age;
public Person(int ID, string Name, int Age)
{
_ID = ID;
_Name = Name;
_Age = Age;
}
public int ID
{
set { _ID = value; }
get { return _ID; }
}
public string Name
{
set { _Name = value; }
get { return _Name; }
}
public int Age
{
set { _Age = value; }
get { return _Age; }
}
public override string ToString()
{
return string.Format("ID:{0},Name:{1},Age:{2}", _ID, _Name, _Age);
}