LINQ | Element Operator | SingleOrDefault
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 SingleOrDefault operator is used to return the single element of the collection or sequence. Basically, it returns the single element which specifies the given condition. Or return the default value if the given collection or sequence does not contain any value. This method can be overloaded in two different ways:
- SingleOrDefault<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>): This method returns the only element of the collection or sequence which specifies the given condition and will throw an exception if more than one element exists that specifies the given condition.
- SingleOrDefault<TSource>(IEnumerable<TSource>): This method returns the only element of a the given sequence or collection, and throws an exception if there is more than one element present in the sequence or collection.
- 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.
- It throws an InvalidOperationException if it contains more than one element that specifies the given condition or more than one element present in the given sequence or collection.
- The default value of the reference types and the nullable types is null.
Element: 777 Element: 2 Element: 0
Employee name: Anupriya