对与list<>泛型的一些操作方法

如果自己定义了一个结构

 1 public struct iPoint
 2     {
 3         private SinglePoint _c;
 4         /// <summary>
 5         /// 当前点的坐标
 6         /// </summary>
 7         public SinglePoint C
 8         {
 9             get { return _c; }
10             set { _c = value; }
11         }
12         public iPoint(SinglePoint _c)
13         {
14                        this._c = _c;
15         }
16     }
17     public struct SinglePoint
18     {
19         private int _y;
20         private int _x;
21         public int Y
22         {
23             get { return _y; }
24             set { _y = value; }
25         }
26         public int X
27         {
28             get { return _x; }
29             set { _x = value; }
30         }
31         public SinglePoint(int _y, int _x)
32         {
33             this._y = _y;
34             this._x = _x;
35         }
36     }

但如果要iPoint[] list=new iPoint[1];这里势必要声明数组的初始大小,这样在实际操作中就比较麻烦,它不要javascript里的数组那样灵活。这个时候就需要用到泛型list<>来做一些处理,但是泛型也有很多不便,为了能记住我将泛型一些简单的操作记录下来
这些操作包括:
1.list<>.find();
2.list<>.sort();
先说find(),先声明一个list
1  List<iPoint> List = new List<iPoint>();
这里当find的时候会发现 public T Find(Predicate<T> match); 这个Predicate<T> match我们改怎么处理呢?
下面我给出一个示例:我们首先要先建立一个finder,我们仅比较struct ipoint里的C的坐标是否相等 其他我们不做比较!
 1 public class Finder
 2     {
 3         private iPoint _c;
 4         /// <summary>
 5         /// 当前点的坐标
 6         /// </summary>
 7         public iPoint C
 8         {
 9             get { return _c; }
10             set { _c = value; }
11         }
12         public Finder(iPoint cPoint)
13         {
14             this._c = cPoint;
15         }
16         public bool FindCurrentPoint(iPoint CurrPoint)
17         {
18             if (C.C.X == CurrPoint.C.X && C.C.Y == CurrPoint.C.Y)
19             {
20                 return true;
21             }
22             else
23             {
24                 return false;
25             }
26         }
27     }
这里开始查找:
1 iPoint tempPoint = new iPoint(1,2);
2             Finder ifinder=new Finder(tempPoint);
3             iPoint findRes= ClosedList.Find( new Predicate<iPoint>(ifinder.FindCurrentPoint));
OK,这里就找到了Y=1,X=2的iPoint对象了。
    再来说sort()
    我们要先建立一个继承自IComparer<>的类
    
 public class FComparer : IComparer<iPoint>
        
{
            
//实现C.X升序
            public int Compare(iPoint x, iPoint y)
            
{
                
return (x.C.X.CompareTo(y.C.X));
            }

        }
调用就更简单了
只需要
1 list.Sort(new FComparer());
就可以了,至于为什么要这样写,我也说不出个所以然来,先记下来用的多了就会了!

posted on 2008-07-01 17:59  Tobin  阅读(1604)  评论(1编辑  收藏  举报

导航