Array.Find and FindAll
Learn to find elements matching a condition with Array.Find and FindAll.
Array.Find and FindAll
Array.Find returns the first element in an array that matches a condition. The condition is given as a predicate: a lambda that takes one parameter and returns a bool. The call Array.Find(nums, n => n > 10) returns the first element greater than 10; if none is found, the default value of the type is returned.
Array.FindAll returns all matching elements as a new array. Find gives a single value, FindAll gives an array.
Lambda and predicate
A predicate is a function that takes one parameter and returns a bool. In C# it is most often written as a lambda expression: n => n > 10. The n on the left of the arrow is the parameter, the n > 10 on the right is the returned bool value.
This lambda is passed as the second parameter to methods like Array.Find, Array.FindAll and Array.FindIndex. The condition is evaluated for each element separately.
Exercise Find the large numbers
On the given int[] nums = { 3, 8, 15, 22, 7 }; array, find all elements greater than 10 with Array.FindAll(nums, n => n > 10) and print big.Length with Console.WriteLine. You must use a lambda.
Show example solution
Get the array with int[] big = Array.FindAll(nums, n => n > 10);, then print the count with Console.WriteLine(big.Length);.
Example solution:
using System;
class Program
{
static void Main()
{
int[] nums = { 3, 8, 15, 22, 7 };
// Find elements greater than 10 with FindAll and print the count
int[] big = Array.FindAll(nums, n => n > 10);
Console.WriteLine(big.Length);
}
}
Test yourself
-
Match each method to its meaning
- Array.Find
- First match
- Array.FindAll
- All matches
- Array.FindIndex
- First index
- n => n > 10
- Predicate
-
What does Array.Find print?
int[] nums = { 5, 12, 8, 20 }; int first = Array.Find(nums, n => n > 10); Console.WriteLine(first);- 12
- 5
- 8
- 20
Show answer
12 — Correct. The first element greater than 10 is 12.
-
FindAll call
int[] nums = { 5, 12, 8, 20 }; int[] big = ____; Console.WriteLine(big.Length);Show answer
int[] nums = { 5, 12, 8, 20 }; int[] big = Array.FindAll(nums, n => n > 10); Console.WriteLine(big.Length);