zoukankan      html  css  js  c++  java
  • 集合中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
  • 相关阅读:
    Mac系统下安装和卸载HomeBrew的方法
    .NET笔试题集(五)
    .NET笔试题集(四)
    .NET笔试题集(二)
    .NET笔试题集(三)
    .NET笔试题集(一)
    C# 文件操作方法
    MD5 加密的两种方法
    jquery 元素选择器集合
    Jquery元素追加和删除
  • 原文地址:https://www.cnblogs.com/mandel/p/3580156.html
Copyright © 2011-2022 走看看