一个例子简单说明一下List<>中Sort()、Find()、FindAll()、Exist()的使用方法:
List<T>.Sort() → 排序T
List<T>.Find() → 找出一个T
List<T>.FindAll() →找出多个T
List<T>.Exist() →判断T是否存在
示例代码: 页面文件aspx
<form id="form1" runat="server"> <div> 原始資料: <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </div> </form>
aspx.cs 代码:
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 pin 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 pin 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); }
相关阅读 >>
asp.net core mvc中如何把二级域名绑定到特定的控制器上
asp.net中sqldatareader生成动态lambda表达式的实例详解
asp.net mvc 遇到json循环调用的问题应该怎么解决?
更多相关阅读请进入《C#》频道 >>
C#高级编程(第11版) C# 7 & .NET Core 2.0(.NET开发经典名著)
作者:[美]克里斯琴·内格尔(Christian Nagel)著。出版时间:2019年3月。