List.Find(),FindAll(),Exist()

代码

namespace ListMethod
{
    
public partial class _Default : 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",20));
            lstPerson.Add(
new Person(3,"ASP.NEt",30));
            lstPerson.Add(
new Person(4,"Dotblogs",40));

            
//原始资料
            this.gv.DataSource = lstPerson;
            
this.gv.DataBind();

            
//List<T>.Find()
            
//find out the person whose name is puma
            Response.Write("Find out name = 'puma'");
            
//选择单条记录
            int i = lstPerson.Find((Person p) => { return p.Name == @"puma"; }).Age;
            
// 选择多条记录
            int count = lstPerson.FindAll((Person p) => { return p.Age > 10; }).Count;
            
//检查是否存在,返回Bool
            string result = lstPerson.Exists((Person p) => { return p.Name == @"F6";}).ToString();

            lstPerson.Sort((Person p1, Person p2) 
=> { return Comparer<string>.Default.Compare(p1.Name,p2.Name); });
            Response.Write(
"The count is "+i.ToString()+"<br/>");

            Response.Write(
"The age > 10,Count= "+count.ToString()+"<br/>");
            Response.Write(
"Exist the person whose name = F6,result = "+result+"<br/>");

        }
    }
}
///////////////////

namespace ListMethod
{
    
public class Person
    {
        
private int id;
        
private string name;
        
private int age;

        
public Person(int id, string name, int age)
        {
            
this.id = id;
            
this.name = name;
            
this.age = age;
        }

        
public int ID
        {
            
set { this.id = value; }
            
get { return this.id; }
        }

        
public string Name
        {
            
set { this.name = value; }
            
get { return this.name; }
        }

        
public int Age
        {
            
set { this.age = value; }
            
get { return this.age; }
        }

        
public override string ToString()
        {
            
return String.Format("ID:{0},Name:{1},Age:{2}",id,name,age);
        }
       
    }
}
原文地址:https://www.cnblogs.com/binlyzhuo/p/1686505.html