Tuesday, March 19, 2013

Array find method

using System;

class Program
{
    static void Main()
    {
// // Use this array of string references. //
string[] array1 = { "cat", "dog", "carrot", "bird" };
// // Find first element starting with substring. //
string value1 = Array.Find(array1,
    element => element.StartsWith("car", StringComparison.Ordinal));
// // Find first element of three characters length. //
string value2 = Array.Find(array1,
    element => element.Length == 3);
// // Find all elements not greater than four letters long. //
string[] array2 = Array.FindAll(array1,
    element => element.Length <= 4);

Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(string.Join(",", array2));
    }
}

Output

carrot
cat
cat,dog,bird


using System;

class Program
{
    static void Main()
    {
string[] array = { "dot", "net", "perls" };
// Find last string of length 3.
string result = Array.FindLast(array, s => s.Length == 3);
Console.WriteLine(result);
    }
}

Output

net

No comments:

Post a Comment