Javatpoint Logo
Javatpoint Logo

LINQ SingleOrDefault Method

In LINQ, SingleOrDefault() method is used to return the single element. In case if there are no elements present in the list/collection, then this will return more than one element and will throw an exception like a Single () method.

Syntax of LINQ SingleOrDefault() Method

Here is the syntax of using the LINQ SingleOrDefault() method to get the single element from the collection.

In the above syntax, we will return the single element from the collection "objList". And if the collection does not contain any element, then it will return the default value.

Example of LINQ SingleOrDefault() Method

Here is the example of the LINQ SingleOrDefault method to get a single element from the collection when an element is not present in the collection.

In the above example, we are trying to get the single element from the two lists (objStudent,objList) objects by using the LINQ SingleOrDefault() method

OUTPUT:

LINQ SingleOrDefault() Method

The LINQ SingleOrDefault() method will throw the InvalidOperationException error in case if the list/collection returns more than one element.

If we run the above code, it will throw the InvalidOperationException error because "objlist" returns the more than one value.

OUTPUT:

LINQ SingleOrDefault() Method
Next TopicLINQ DefaultEmpty




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA