集合中Predicate<T>委托的使用

  Predicate<T>委托表示定义一组条件并确定指定对象是否符合这些条件的方法。或者说是用于定义要搜索的元素的条件。

  Array有Array.Find<T>(T[] array,Predicate<T> match)方法,List<T>有List<T>.Find(Predicate<T> match)方法使用该委托。

  Code:

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             //List<T>.Find
 6             Random r = new Random();
 7             List<int> listInt = new List<int>();
 8             for (int i = 0; i < 10; i++)
 9             {
10                 listInt.Add(r.Next(1, 10));
11                 listInt.Add(r.Next(10, 20));
12             }
13             int _ret = listInt.Find(delegate(int num) //匿名方法
14              {
15                  return num == 10;
16              });
17             Console.WriteLine(_ret);
18             _ret=listInt.Where(delegate(int num) //使用Where也可以获取
19             {
20                 return num == 10;
21             }).First();
22             Console.WriteLine(_ret);
23 
24             List<int> _retList = listInt.FindAll(delegate(int num)
25             {
26                 return num > 10;
27             });
28             int _retSum = 0;
29             _retList.ForEach((num) => //Lambda 
30             {
31                 _retSum = _retSum + num;
32             });
33             Console.WriteLine(_retSum);
34 
35            
36             //Array.Find
37             Point[] points = { new Point(100, 200), 
38                          new Point(150, 250), new Point(250, 375), 
39                          new Point(275, 395), new Point(295, 450) };
40 
41             Point first = Array.Find(points, x => x.X * x.Y > 100000);
42             Console.WriteLine(first.X + "-" + first.Y);
43             Console.ReadKey();
44         }
45     }
View Code

 

posted on 2014-03-04 12:54  象山  阅读(409)  评论(0编辑  收藏  举报

导航