First and Last
- Note:
Returns the first and last elements of a collection
When used without any arguments, First returns the first element of the collection, and Last returns the last
First and Last can also take a predicate (function that returns true or false) to find the first or last element that satisfies certain conditions -
In this example, First returns the first even number, and Lst the last odd number.
The lamda expressions n => n % 2 and n => n % 2 != 0 are the predicates that define the conditions.
The above example will return the name of the first student who is older than 21.
First and Last will throw an exception if there is no element in the collection that satisfies the condition.
FirstOrDefault & LastOrDefault
These are very similar to First and Last but instead of throwing an exception if no suitable element is found, it returns the default value for the type (null for reference types and zero for numeric value types).