First
If you ever need to return the first element in an array or list, First
is a useful method to use as it does just that.
Basic example
For this list, using First
will return the first element in the array which will be 2
.
Live example: https://dotnetfiddle.net/SbPB7D
var numbers = new[] { 2, 4, 6, 8, 10 };
int first = numbers.First();
//output: 2
First with Predicate
Just like the First
method where it returns the first element of an array or list, you can use the First
operator to return the first element based on a boolean condition.
In this example, we have a list of people and we just want to pull out Carrie from the list which has an id of 3.
We can perform this with either a Where clause with a combination of a .First
or alternatively we can use the .First
with a predicate.
Where with First
Here's an example with the combination of using .Where
and .First
.
Live example: https://dotnetfiddle.net/dOQW5C
var people = new[]
{
new
{
Id =1, Name = "Vernon", Gender = "Male", CountryCode = "GB",
},
new
{
Id = 2, Name = "Carrie", Gender = "Female", CountryCode = "CA"
},
new
{
Id = 3, Name = "Joanna", Gender = "Female", CountryCode = "US"
},
};
var carrie = people.Where(p => p.Id == 3).First();
//output: carrie
First with predicate example
Here's an example with a predicate.
Live example: https://dotnetfiddle.net/5Xvty9
var people = new[]
{
new
{
Id = 1, Name = "Vernon", Gender = "Male", CountryCode = "GB",
},
new
{
Id = 2, Name = "Carrie", Gender = "Female", CountryCode = "CA"
},
new
{
Id = 3, Name = "Joanna", Gender = "Female", CountryCode = "US"
},
};
var carrie = people.First(p => p.Id == 3);
//output: carrie