首页 > 代码库 > List<T> 的扩展方法
List<T> 的扩展方法
//List<T>.Take(m) //取出 前m行
IEnumerable<Person> takeList = lstPerson.Take(4);
foreach (Person s in takeList) { Console.WriteLine("element in takeList: " + s); }
//List<T>.Where()
Console.WriteLine("找出Name=‘puma‘的Person ");
IEnumerable<Person> whereList = lstPerson.Where(name => { if (name.Name == "puma") { return true; } else { return false; } });
Console.WriteLine(lstPerson.Where(name => { if (name.Name == "puma") { return true; } else { return false; } }));
foreach (Person s in lstPerson) { Console.WriteLine("element in subList: " + s); }
//List<T>.Find() //找出Name=‘puma‘的Person
Console.WriteLine("找出Name=‘puma‘的Person→ ");
Console.WriteLine(lstPerson.Find(delegate (Person p) { return p.Name == "puma"; }).ToString() + "<p>");
//List<T>.FindAll() //找出Age>10的數目
Console.WriteLine("找出Age>10的數目→ ");
Console.WriteLine(lstPerson.FindAll(delegate (Person p) { return p.Age > 10; }).Count.ToString() + "<p>");
//List<T>.Exists() //檢查Name=‘F6‘是否存在
Console.WriteLine("檢查Name=‘F6‘是否存在→ ");
Console.WriteLine(lstPerson.Exists(delegate (Person p) { return p.Name == "F6"; }).ToString() + "<p>");
//依Name升冪排序
Console.WriteLine("<p>依Name升冪排序↑<br/>");
lstPerson.Sort(delegate (Person p1, Person p2) { return Comparer<string>.Default.Compare(p1.Name, p2.Name); });
foreach (Person p in lstPerson) { Console.WriteLine(p.ToString() + "<br/>"); }
//List<T>.Sort() //依Name降冪排序
Console.WriteLine("<p>依Name降冪排序↓<br/>");
lstPerson.Sort(delegate (Person p1, Person p2) { return Comparer<string>.Default.Compare(p2.Name, p1.Name); });
foreach (Person p in lstPerson) { Console.WriteLine(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); }
}
List<T> 的扩展方法