LINQ | Element Operator | FirstOrDefault
The element operators are used to return a single, or a specific element from the sequence or collection. For example, in a school when we ask, who is the principal? Then there will be only one person that will be the principal of the school. So the number of students is a collection and the principal is the only result that comes from the collection.
The LINQ Standard Query Operator supports 8 types of element operators:
The FirstOrDefault operator is used to return the first element of the given collection or sequence. Or it can also return the first element according to the given condition. And it provides a default value if the given collection or sequence does not contain any element or if the collection or sequence does not contain the element which specifies the given condition. Or we can say that the FirstOrDefault Operator is created to overcome the InvalidOperationException problem of the First operator. This method can be overloaded in two different ways:
- FirstOrDefault<TSource>(IEnumerable<TSource>): This method returns the first element of the given sequence or collection without any condition. Or returns the default value if the given collection or sequence does not contain any element.
- FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>): This method returns the first element which specifies the given condition. Or returns the default value if the collection does not contain the element which specifies the given condition.
- It does not support query syntax in C# and VB.Net languages.
- It support method syntax in both C# and VB.Net languages.
- It present in both the Queryable and Enumerable class.
- If the given collection contain a null element, then this method will throw an ArgumentNullException.
- The default value of the reference types and the nullable types is null.
Value: 44 Default value: 0
Employee Name: Anjita