using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class GenericList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
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() + "<p>");
//List<T>.FindAll()
//找出Age>10的數目
Response.Write("找出Age>10的數目→ ");
Response.Write(lstPerson.FindAll(delegate(Person p) { return p.Age > 10; }).Count.ToString() + "<p>");
//List<T>.Exists()
//檢查Name='F6'是否存在
Response.Write("檢查Name='F6'是否存在→ ");
Response.Write(lstPerson.Exists(delegate(Person p) { return p.Name == "F6"; }).ToString() + "<p>");
//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/>");
}
}
}
public 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);
}
}
原始文章出自於此
沒有留言:
張貼留言