Array Find

In this chapter you will learn:

  1. How to filter array with delegate
  2. How to filter array with anonymous method
  3. Find with lambda expression

Find with delegate

In the following example, we search an array of strings for a name containing the letter "a":

using System;/*j a  va 2  s .  c o  m*/
using System.Collections;

class Sample
{
    public static void Main()
    {
        string[] names = { "Java", "C#", "Javascript" };
        string match = Array.Find(names, ContainsA);
        Console.WriteLine(match);  

    }
    static bool ContainsA(string name)
    {
        return name.Contains("a");
    }
}

The output:

Array.Find with anonymous method

Here's the same code shortened with an anonymous method:

using System;// j  a  va 2  s. c  om
using System.Collections;

class Sample
{
    public static void Main()
    {
        string[] names = { "Java", "C#", "Javascript" };
        string match = Array.Find(names, delegate(string name) { return name.Contains("a"); });
        Console.WriteLine(match);

    }

}

The output:

Find with lambda expression

A lambda expression shortens it further:

using System;/* ja  v  a 2 s.c om*/
using System.Collections;

class Sample
{
    public static void Main()
    {
        string[] names = { "Java", "C#", "Javascript" };
        string match = Array.Find(names, n => n.Contains("a"));
        Console.WriteLine(match);
    }

}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to compare two arrays with Array SequenceEqual method
Home » C# Tutorial » Array
Array
Array loop
Array dimension
Jagged Array
Array length
Array Index
Array rank
Array foreach loop
Array ForEach Action
Array lowerbound and upperbound
Array Sort
Array search with IndexOf methods
Array binary search
Array copy
Array clone
Array reverse
Array ConvertAll action
Array Find
Array SequenceEqual