C# First (Get Matching Element With Lambda)

Use the First extension method. First returns the first element that matches a lambda.
First gets the first matching object. These objects can be of any type. We access the First extension method in the System.Linq namespace. The argument to First is a Predicate instance—it can be specified in the lambda syntax.Predicate
Example. Initially here we look at a complete program that uses a List of object instances and then searches this List with 2 different methods. The 2 methods shown efficiently test each element in the List for a match.

Animal: The Animal class is declared at the top, and it includes 2 automatically implemented properties.

Next: An example List containing 3 Animal objects is instantiated. For the example, it is a static method.

Static

GetAnimal1: This method is called, and returns the first matching Animal with a Name of "Ape". The correct object is printed.

GetAnimal2: This method is then called, and it finds the first Animal with the Name of "Camel". The correct Animal is returned.

C# program that uses First on class 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() { // A // Get Ape from collection Animal a1 = GetAnimal1("Ape"); Console.WriteLine(a1); // B // Get Camel from collection 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); } } Output Name=Ape,Age=3 Name=Camel,Age=5
Lambda expressions. The second method uses an extension method called First, which has an overload that accepts a lambda expression specifying which objects will match. The lambda expression, which uses =>, can be read as "goes to".

Note: The "a" in the expression is a variable identifier, and you could easily change it.

And: On the right side of the expression, the Name is tested against the parameter n.

Lambda Expression
FirstOrDefault. The C# language provides another extension method called FirstOrDefault in the System.Linq namespace. This method provides the same functionality as First but will return the default value for a type if there are no elements.FirstOrDefault

Tip: This method is excellent for determining the "best match" from a sorted or filtered query.

Summary. We can successfully rewrite foreach-loops into First method calls. We saw some lambda calculus and then proved the correctness of both methods. We used some interesting syntax, such as the collection initializer syntax.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls