C#中List的用法

C#/ASP.NET中List<T>真的非常好用。

一个例子简单说明一下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);
    }

欢迎分享,(木庄网络博客交流QQ群:562366239

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论