TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# SingleOrDefault

This C# example program uses the SingleOrDefault extension method. It requires System.Linq.

SingleOrDefault is similar to Single.

On empty collections, it returns the default value for the type. With it you receive the single matching element, or the default value if no element is found.

Example. This program allocates an array of three integers. Next, the SingleOrDefault method is called. A Predicate is specified to search for a single element equal to 5. No such element exists, so the default value of int is returned: 0.

Int ArrayPredicate

Next, SingleOrDefault is called to find an element of value 1—one such element exists. Finally, SingleOrDefault is used to find an element >= 1. Because three elements match this condition, an exception is thrown.

Lambda ExpressionInvalidOperationException

C# program that uses SingleOrDefault method

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	int[] array = { 1, 2, 3 };

	// Default is returned if no element found.
	int a = array.SingleOrDefault(element => element == 5);
	Console.WriteLine(a);

	// Value is returned if one is found.
	int b = array.SingleOrDefault(element => element == 1);
	Console.WriteLine(b);

	try
	{
	    // Exception is thrown if more than one is found.
	    int c = array.SingleOrDefault(element => element >= 1);
	}
	catch (Exception ex)
	{
	    Console.WriteLine(ex.GetType());
	}
    }
}

Output

0
1
System.InvalidOperationException

Single. What is the difference between Single and SingleOrDefault? The difference is what happens when zero matching elements are found. With Single, an exception is thrown in this case. But with SingleOrDefault, the default value is returned.

Note: For ints, the default value is 0. You can find default values with the default operator.

Single MethodDefault

Summary. SingleOrDefault helps ensure zero or one elements exist matching a condition. As with Single, it can be used with no parameters to match all elements. Its behavior on multiple matches, which results in an exception, can be confusing.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf