2010年12月31日 星期五

Generic List的排序與搜尋

假設有一Person類別
Person類別
public class Person
{
public int age;
public string name;

public Person(int age, string name)
{
this.age = age;
this.name = name;
}
}
List
 people = new List
();

people.Add(new Person(50, "Fred"));
people.Add(new Person(30, "John"));
people.Add(new Person(26, "Andrew"));
people.Add(new Person(24, "Xavier"));
people.Add(new Person(5, "Mark"));
people.Add(new Person(6, "Cameron"));
程式碼
Console.WriteLine("Unsorted list");
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

//搜尋小於25歲的人
List
 young = people.FindAll(delegate(Person p) { return p.age < 25; });
Console.WriteLine("Age is less than 25");
young.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

//依姓名排序
Console.WriteLine("Sorted list, by name");
people.Sort(delegate(Person p1, Person p2) { return p1.name.CompareTo(p2.name); });
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });

//依歲數排序
people.Sort(delegate(Person p1, Person p2) { return p1.age.CompareTo(p2.age); });
Console.WriteLine("Sorted list, by age");
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}", p.age, p.name)); });
輸出
Unsorted list
50 Fred
30 John
26 Andrew
24 Xavier
5 Mark
6 Cameron

Age is less than 25
24 Xavier
5 Mark
6 Cameron

Sorted list, by name
26 Andrew
6 Cameron
50 Fred
30 John
5 Mark
24 Xavier

Sorted list, by age
5 Mark
6 Cameron
24 Xavier
26 Andrew
30 John
50 Fred

沒有留言: