Array Find
In this chapter you will learn:
- How to filter array with delegate
- How to filter array with anonymous method
- 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:
Home » C# Tutorial » Array