First. This extension method gets the first matching object. These objects can be of any type. We access the First extension method in the System.Linq namespace.
Method details. The argument to First is a Predicate instance—it can be specified with lambda syntax. A predicate returns true or false.
Input and output. Imagine an array of several objects. The objects have string names: Camel, Ape, Dog. The first one matching Ape is the second object.
First(Ape):
Camel
Ape
Dog
An example. To begin, we create a List of object instances. Then we search the List with 2 methods—the methods tests each element for a match.
Info The Animal class is declared at the top. It includes 2 automatically implemented properties.
Part 1 GetAnimal1 is called, and it returns the first matching Animal with a Name of "Ape." The correct object is printed.
Part 2 GetAnimal2 is called. It finds the first Animal with the Name of "Camel." The correct Animal is returned.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
class Animal
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return string.Format("Name={0},Age={1}", Name, Age);
}
};
static List<Animal> _animals = new List<Animal>()
{
new Animal()
{
Name = "Camel",
Age = 5
},
new Animal()
{
Name = "Ape",
Age = 3
},
new Animal()
{
Name = "Dog",
Age = 6
}
};
static void Main()
{
// Part A: get animal with foreach.
Animal a1 = GetAnimal1("Ape");
Console.WriteLine(a1);
// Part B: get animal with First method.
Animal a2 = GetAnimal2("Camel");
Console.WriteLine(a2);
}
static Animal GetAnimal1(string n)
{
foreach (Animal a in _animals)
{
if (a.Name == n)
{
return a;
}
}
throw new Exception(n);
}
static Animal GetAnimal2(string n)
{
return _animals.First(a => a.Name == n);
}
}Name=Ape,Age=3
Name=Camel,Age=5
Lambda notes. First() accepts a lambda expression specifying which objects will match. We can omit the lambda expression to not filter elements.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 20, 2023 (edit).