📌  相关文章
📜  C#|检查数组是否包含符合指定条件的元素

📅  最后修改于: 2021-05-29 17:51:07             🧑  作者: Mango

Array.Exists(T [],Predicate )方法用于检查指定的数组是否包含与指定谓词定义的条件匹配的元素。

句法:

public static bool Exists (T[] array, Predicate match);

参数:

返回值:该方法的返回类型为System.Boolean 。如果数组包含一个或多个与指定谓词定义的条件匹配的元素,则返回true。否则,返回false

异常:如果array的值为null,或者match的值为null,则此方法将提供ArgumentNullException

下面给出了一些示例,以更好地理解实现:

范例1:

// C# program to illustrate the 
// Array.Exists(T[], Predicate) Method
using System;
  
class GFG {
  
    // Main method
    static public void Main()
    {
  
        // Create and initialize array
        string[] language = {"Ruby", "C", "C++", "Java",
                             "Perl", "C#", "Python", "PHP"};
  
        // Display language array
        Console.WriteLine("Display the array:");
        foreach(string i in language)
        {
            Console.WriteLine(i);
        }
  
        // Display and check the given elements
        // present in the array or not
          
        // Using Exists() method
        Console.WriteLine("Is Ruby part of language: {0}",
                          Array.Exists(language, element => element == "Ruby"));
  
        Console.WriteLine("Is VB part of language: {0}",
                          Array.Exists(language, element => element == "VB"));
    }
}
输出:
Display the array:
Ruby
C
C++
Java
Perl
C#
Python
PHP
Is Ruby part of language: True
Is VB part of language: False

范例2:

// C# program to illustrate the 
// Array.Exists(T[], Predicate) Method
using System;
  
public class GFG {
  
// Main method
static public void Main()
{
      
    // Create and initialize array
    string[] ds = {"Array", "Queue", "LinkedList",
                               "Stack", "Graph" };
      
    // Display ds array
    Console.WriteLine("Given Array: ");
      
    foreach(string i in ds)
    {
        Console.WriteLine(i);
    }
      
    // Display and check the given elements with the
    // specified letter is present in the array or not
    // Using Exists() method
    Console.WriteLine("Is element start with L letter is present in array: {0}",
                      Array.Exists(ds, element => element.StartsWith("L")));
      
    Console.WriteLine("Is element start with O letter is present in array: {0}",
                      Array.Exists(ds, element => element.StartsWith("O")));
}
}
输出:
Given Array: 
Array
Queue
LinkedList
Stack
Graph
Is element start with L letter is present in array: True
Is element start with O letter is present in array: False

注意:此方法是O(n)运算,其中n是数组的长度。

参考: https://docs.microsoft.com/zh-cn/dotnet/api/system.array.exists?view=netcore-2.1#definition