C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
StaticGetAnimal1: 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
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 ExpressionTip: This method is excellent for determining the "best match" from a sorted or filtered query.