This method is used to search for an element that matches the conditions defined by the specified predicate and returns the first occurrence within the entire Array.
Syntax:
public static T Find (T[] array, Predicate<T> match);
Here, T is the type of element of the array.
Parameters:
array: It is the one-dimensional, zero-based array to search.
match: It is the predicate that defines the conditions of the element to search for.
Return Value: This method return the first element that matches the conditions defined by the specified predicate if it is found. Otherwise, it returns the default value for type T.
Exception: This method throws ArgumentNullException if the array is null or match is null.
Below programs illustrate the use of Array.Find(T[], Predicate) Method:
Example 1:
CSharp
using System;
using System.Collections.Generic;
public class GFG {
public static void Main()
{
try {
String[] myArr = { "Sun" , "Mon" , "Tue" , "Thu" };
Console.WriteLine( "Initial Array:" );
PrintIndexAndValues(myArr);
string value = Array.Find(myArr,
element => element.StartsWith( "S" ,
StringComparison.Ordinal));
Console.Write( "Element: " );
Console.Write( "{0}" , value);
}
catch (ArgumentNullException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
public static void PrintIndexAndValues(String[] myArr)
{
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine( "{0}" , myArr[i]);
}
Console.WriteLine();
}
}
|
Output:
Initial Array:
Sun
Mon
Tue
Thu
Element: Sun
Example 2:
CSharp
using System;
using System.Collections.Generic;
public class GFG {
public static void Main()
{
try {
String[] myArr = null ;
string value = Array.Find(myArr,
element => element.StartsWith( "S" ,
StringComparison.Ordinal));
Console.Write( "Element: " );
Console.Write( "{0}" , value);
}
catch (ArgumentNullException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
public static void PrintIndexAndValues(String[] myArr)
{
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine( "{0}" , myArr[i]);
}
Console.WriteLine();
}
}
|
Output:
Exception Thrown: System.ArgumentNullException
Reference:
Last Updated :
05 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...