In LINQ, element operators are useful for returning a first/last element of the list, a single element from the collection, or a specific element based on index value from a collection.
In LINQ, we have different types of element operators available those are
Using these element operators, we can get list/collection items at a specific position. The following table shows more detailed information related to element operators.
Operator | Description |
---|---|
First | It returns the first element in sequence or the first element from the collection based on the specified condition. |
FirstOrDefault | It's same as First, but it returns the default value if no element is found in the collection. |
Last | It returns the last elements in sequence or the last element from the list based on matching criteria. |
LastOrDefault | It's same as Last, but it returns a default value if no element is found in the collection. |
ElementAt | It returns an element from the list based on the specified index position. |
ElementAtOrDefault | It's same as ElementAt, but it returns the default value if no element is present at the specified index of the collection. |
Single | It returns a single specific element from the collection. |
SingleOrDefault | It's same as Single, but it returns a default value if no element is found in the collection. |
DefaultIfEmpty | It returns the default value if the list or collection contains empty or null values. |
We will learn all the element operators in-detail in further chapters with examples.
We will be studying each of them with a demo to get a clear understating of the operators. So let’s start with a demo.