[转]C# 中使用委托对List<>进行排序和筛选
一、使用委托对List<>进行排序
现有类A,含三个属性,分别是NO,AGE,NAME,现在要求按照这个顺序排序(既先比较NO,如果相同比较AGE,如果AGE相同就比较NAME)。
类A的代码:
1: class A
2: {
3: private string _name;
4: public string NAME
5: {
6: get { return _name; }
7: set { _name = value; }
8: }
9:
10: private int _age;
11: public int AGE
12: {
13: get { return _age; }
14: set { _age = value; }
15: }
16:
17: private int _no;
18: public int NO
19: {
20: get { return _no; }
21: set { _no = value; }
22: }
23:
24: public A(int no, int age, string name)
25: {
26: this.NO = no;
27: this.AGE = age;
28: this.NAME = name;
29: }
30: }
构造相应对象,对其进行排序测试:
1: static void Main(string[] args)
2: {
3: //构造数据
4: List<A> list = new List<A>();
5: list.Add(new A(20, 20, "00001"));
6: list.Add(new A(18, 50, "00003"));
7: list.Add(new A(20, 19, "00004"));
8: list.Add(new A(21, 21, "00005"));
9: list.Add(new A(19, 19, "00006"));
10: list.Add(new A(99, 19, "00007"));
11: list.Add(new A(19, 19, "00008"));
12: list.Add(new A(38, 50, "00009"));
13:
14: //进行排序
15: list.Sort(delegate(A a1, A a2)
16: {
17: if (a1.NO.CompareTo(a2.NO) != 0)
18: return a1.NO.CompareTo(a2.NO);
19: else if (a1.AGE.CompareTo(a2.AGE) != 0)
20: return a1.AGE.CompareTo(a2.AGE);
21: else
22: return a1.NAME.CompareTo(a2.NAME);
23: });
24:
25: //打印输出
26: foreach (A a in list)
27: {
28: Console.WriteLine(a.NO + " " + a.AGE + " " + a.NAME);
29: }
30:
31: Console.ReadLine();
32: }
其实这是用委托表示的方法对 List 的元素进行排序。内部实现则为QuickSort 算法。
详情可参考:http://msdn.microsoft.com/zh-cn/library/w56d4y5z(VS.80).aspx
原文地址:http://www.cnblogs.com/liaozh/archive/2009/12/08/1619679.html
二、使用委托对List<>进行筛选
C#里 List 筛选是很简单的事情,不用自已写循环去遍历,利用.net的特性 list.FindAll 可以很方便的实现。
1: /// <summary>
2: /// 根据匹配条件获得子列表
3: /// </summary>
4: /// <param name="list"></param>
5: /// <returns></returns>
6: private List<BaseInfo> selectList(List<BaseInfo> list)
7: {
8: string name = txtName.Text.Trim();
9: string nation = txtNation.Text.Trim();
10:
11: return list.FindAll(delegate(BaseInfo info)
12: {
13: if ((string.IsNullOrEmpty(name) || info.Name.IndexOf(name) != -1) && (string.IsNullOrEmpty(nation) || info.Nation.IndexOf(nation) != -1))
14: {
15: return true;
16: }
17: else
18: {
19: return false;
20: }
21: });
22: }
1: /// <summary>
2: /// 从列表中获得分页数据
3: /// </summary>
4: /// <param name="list"></param>
5: /// <param name="pageIndex"></param>
6: /// <param name="pageSize"></param>
7: /// <returns></returns>
8: private List<BaseInfo> getPageData(List<BaseInfo> list, int pageIndex, int pageSize)
9: {
10: return list.FindAll(delegate(BaseInfo info)
11: {
12: int index = list.IndexOf(info);
13: if (index >= (pageIndex - 1) * pageSize && index < pageIndex * pageSize)
14: {
15: return true;
16: }
17: else
18: {
19: return false;
20: }
21: });
22: }
原文地址:http://lwbpeter.blog.163.com/blog/static/3850821120116183139512/