📜  LINQ |量词运算符|任何

📅  最后修改于: 2021-05-29 21:20:09             🧑  作者: Mango

在LINQ中,量词运算符用于返回一个布尔值,该值表明是否某些或所有元素都满足给定条件。标准查询运算符支持3种不同类型的量词运算符:

  1. 全部
  2. 任何
  3. 包含

任何运营商

Any运算符用于检查序列或集合中的任何元素是否满足给定条件。如果一个或多个元素满足给定条件,则它将返回true。如果任何元素不满足给定条件,则它将返回false。

  • 它以两种不同的类型重载:
    • Any (IEnumerable ):此方法用于检查序列是否包含任何元素。
    • Any (IEnumerable ,Func ):此方法用于检查序列中的任何元素是否满足条件。
  • 它通常与where子句一起使用。
  • 它不支持C#和VB.Net语言的查询语法。
  • 它支持C#和VB.Net语言的方法语法。
  • 它同时存在于Queryable和Enumerable类中。
  • 如果给定的源为null,它将抛出ArgumentNullException。
  • 它不返回值,而是返回true或false。
  • 该运算符的返回类型为System.Boolean

范例1:

// C# program to illustrate the
// use of Any operator
using System;
using System.Linq;
using System.Collections.Generic;
  
class GFG {
  
    // Main Method
    static public void Main()
    {
  
        // Data source
        int[] sequence1 = {34, 56, 77, 88,
                          99, 10, 23, 46};
                            
        string[] sequence2 = {"aa", "oo", "gg",
                             "ww", "jj", "uu"};
                               
        char[] sequence3 = {'c', 'c', 'A',
                                'E', 'u'};
  
        // Check the sequence1 if it 
        // contain any element as 10
        // Using Any operator
        var result1 = sequence1.Any(seq => seq == 10);
  
        Console.WriteLine("Is the given sequence "+
           "contain element as 10 : {0}", result1);
  
        // Check the sequence2 if it 
        // contain any element as "oo"
        // Using Any operator
        var result2 = sequence2.Any(seq => seq == "oo");
  
        Console.WriteLine("Is the given sequence "+
          "contain element as 'oo' : {0}", result2);
  
        // Check the sequence3 if it 
        // contain any element as 'c'
        // Using Any operator
        var result3 = sequence3.Any(seq => seq == 'c');
  
        Console.WriteLine("Is the given sequence "+
          "contain element as 'c' : {0}", result3);
    }
}
输出:
Is the given sequence contain element as 10 : True
Is the given sequence contain element as 'oo' : True
Is the given sequence contain element as 'c' : True

范例2:

// C# program to check the list 
// contain employee data or not
using System;
using System.Linq;
using System.Collections.Generic;
  
// Employee details
public class Employee { }
  
class GFG {
  
    // Main method
    static public void Main()
    {
        List emp = new List() { };
  
        // Query to check this list 
        // contain employee data or not
        // Using Any operator
        var res = emp.Any();
          
        Console.WriteLine("Is the list contain "+
                    "employees data?: {0}", res);
    }
}
输出:
Is the list contain employees data?: False