C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
Example. Initially here we look at a complete program that uses a List of object instances and then searches this List with two different methods. The two methods shown efficiently test each element in the List for a match.
Note: The following code demonstrates the two methods being used and their results being printed.
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
The Animal class is declared at the top, and it includes two automatically implemented properties. These have actual backing stores, but they are implicit. This means they are shorter to type.
Next: An example List containing three Animal objects is instantiated. For the example, it is a static method.
Method 1 above is called, and returns the first matching Animal with a Name of "Ape". The correct object is printed. Method 2 is then called, and it finds the first Animal with the Name of "Camel". The correct Animal is returned.
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.
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.
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.