对存入泛型中的数据进行搜索和排序(Generic)
主要是将两组数组合到list<T>(泛型)中进行搜索和排序
Example
搜索
List<Person> people = new List<Person>();
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"));
List<Person> young = people.FindAll(delegate(Person p) { return p.age < 25 || p.name.Contains("F"); });
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"));
List<Person> young = people.FindAll(delegate(Person p) { return p.age < 25 || p.name.Contains("F"); });
注:上面代码是搜索年龄下于25,或者 名字中包含“F”字母的记录,注意一定要有return语句不要然会报错!
排序
people.Sort(delegate(Person p1, Person p2) { return p1.age.CompareTo(p2.age); });
注:上面代码是按年龄升序排序,将p1.age和p2.age位置互换就变成降序排序了
如:
people.Sort(delegate(Person p1, Person p2) { return p2.age.CompareTo(p1.age); });