Fork me on Github

Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)

Where 方法定义在 System.Linq 命名空间中,并且通常用于 LINQ 查询。
       List<string> fruits =
new List<string> { "apple", "passionfruit", "banana", "mango",
               "orange", "blueberry", "grape", "strawberry" };

       IEnumerable<string> query = fruits.Where(s => s.Length < 6);
foreach (string fruit in query) { Console.WriteLine(fruit); }

 Func<string, bool> 是一个委托类型。Func 是一个泛型委托,它表示一个接受输入参数并返回一个结果的方法。Func<string, bool> 具体表示一个接受一个 string 类型参数并返回 bool 类型结果的方法。

   static void Main(string[] args)
   {
       List<string> fruits =
new List<string> { "apple", "passionfruit", "banana", "mango",
               "orange", "blueberry", "grape", "strawberry" };

       Func<string, bool> predicate = new Func<string, bool>(Condition);

       IEnumerable<string> query = fruits.Where(predicate);
    
       foreach (string fruit in query)
       {
           Console.WriteLine(fruit);
       }
   }

   static bool Condition(string s)
   {
       return s.Length < 6;
   }

 

posted @ 2025-05-19 14:53  昂昂呀  阅读(29)  评论(0)    收藏  举报