In the following example, we search an array of strings for a name containing the letter "a":
using System;
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:
Java
Here's the same code shortened with an anonymous method:
using System;
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);
}
static bool ContainsA(string name)
{
return name.Contains("a");
}
}
The output:
Java
A lambda expression shortens it further:
using System;
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:
Java