List<T>的Sort,Find,Exists等的使用
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)); //List<T>.Find() //找出Name='puma'的Person lstPerson.Find(delegate(Person p) { return p.Name == "puma"; }); //List<T>.FindAll() //找出Age>10 lstPerson.FindAll(delegate(Person p) { return p.Age > 10; }); //List<T>.Exists() //檢查Name='F6'是否存在 lstPerson.Exists(delegate(Person p) { return p.Name == "F6"; }); //List<T>.Sort() //依Name升序排序 lstPerson.Sort(delegate(Person p1, Person p2) { return Comparer<string>.Default.Compare(p1.Name, p2.Name); }); //List<T>.Sort() //依Name降序排序 lstPerson.Sort(delegate(Person p1, Person p2) { return Comparer<string>.Default.Compare(p2.Name, p1.Name); }); 有一个list,格式如list<userType>, 但是这个userType并没有继承自ICompare或者IComparable 等,那如何给这个list排序那? 指定一个类 这个类要继承自ICompare<userType> public class SortUserGroup:IComparer<UserGroup> { /// <summary> /// Sort by AccountID and UserGroupName /// </summary> /// <param name="userGroup1"></param> /// <param name="userGroup2"></param> /// <returns></returns> int IComparer<UserGroupEntityAccess>.Compare(UserGroup userGroup1, UserGroup userGroup2) { if (userGroup1 != null && userGroup2 != null) { if (userGroup1.AccountID == userGroup2.AccountID) return userGroup1.UserGroupName.CompareTo(userGroup2.UserGroupName); else return userGroup1.AccountID > userGroup2.AccountID ? 1 : -1; } return -1; } } 然后: SortUserGroup sortGroup = new SortUserGroup(); List<UserGroup>.Sort(sortUserGroup) 这里是按照UserGroup的AccountID 和 UserGroupName 两个字段排序。