Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • LINQ - Get Started
  • What is LINQ
  • Why LINQ
  • LINQ API
  • LINQ Query Syntax
  • LINQ Method Syntax
  • Lambda Expression
  • Standard Query Operators
  • Where
  • OfType
  • OrderBy
  • ThenBy
  • GroupBy, ToLookup
  • Join
  • GroupJoin
  • Select
  • All, Any
  • Contains
  • Aggregate
  • Average
  • Count
  • Max
  • Sum
  • ElementAt, ElementAtOrDefault
  • First, FirstOrDefault
  • Last, LastOrDefault
  • Single, SingleOrDefault
  • SequenceEqual
  • Concat
  • DefaultIfEmpty
  • Empty, Range, Repeat
  • Distinct
  • Except
  • Intersect
  • Union
  • Skip, SkipWhile
  • Take, TakeWhile
  • Conversion Operators
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Element Operators: Single & SingleOrDefault

Element OperatorsDescription
SingleReturns the only element from a collection, or the only element that satisfies a condition. If Single() found no elements or more than one elements in the collection then throws InvalidOperationException.
SingleOrDefaultThe same as Single, except that it returns a default value of a specified generic type, instead of throwing an exception if no element found for the specified condition. However, it will thrown InvalidOperationException if it found more than one element for the specified condition in the collection.

The Single and SingleOrDefault have two overload methods. The first overload method doesn't take any input parameter and returns a single element in the collection. The second overload method takes the lambda expression as a predicate delegate that specifies the condition and returns a single element that satisfies the specified condition.

Single() Á SingleOrDefault() Overloads:
public static TSource Single<TSource>(this IEnumerable<TSource> source);public static TSource Single<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source);public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

The Single returns the only element from a collection, or the only element that satisfies the specified condition. If a given collection includes no elements or more than one elements then Single throws InvalidOperationException.

The SingleOrDefault method does the same thing as Single method. The only difference is that it returns default value of the data type of a collection if a collection is empty, includes more than one element or finds no element or more than one element for the specified condition.

Example: Single in method syntax C#
IList<int> oneElementList = new List<int>() { 7 };
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();

Console.WriteLine("The only element in oneElementList: {0}", oneElementList.Single());
Console.WriteLine("The only element in oneElementList: {0}",
             oneElementList.SingleOrDefault());

Console.WriteLine("Element in emptyList: {0}", emptyList.SingleOrDefault());

Console.WriteLine("The only element which is less than 10 in intList: {0}",
             intList.Single(i => i &lt; 10));

//Followings throw an exception
//Console.WriteLine("The only Element in intList: {0}", intList.Single());
//Console.WriteLine("The only Element in intList: {0}", intList.SingleOrDefault());
//Console.WriteLine("The only Element in emptyList: {0}", emptyList.Single());
Try it
Output:
The only element in oneElementList: 7
The only element in oneElementList: 7
Element in emptyList: 0
The only element which is less than 10 in intList: 7

The following example code throws an exception because Single or SingleOrDefault returns none or multiple elements for the specified condition.

C#: Single() and SingleOrDefault()
IList<int> oneElementList = new List<int>() { 7 };
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();

//following throws error because list contains more than one element which is less than 100
Console.WriteLine("Element less than 100 in intList: {0}", intList.Single(i =&gt; i < 100));

//following throws error because list contains more than one element which is less than 100
Console.WriteLine("Element less than 100 in intList: {0}", 
                                    intList.SingleOrDefault(i => i &lt; 100));

//following throws error because list contains more than one elements
Console.WriteLine("The only Element in intList: {0}", intList.Single());

//following throws error because list contains more than one elements
Console.WriteLine("The only Element in intList: {0}", intList.SingleOrDefault());

//following throws error because list does not contains any element
Console.WriteLine("The only Element in emptyList: {0}", emptyList.Single());
Try it
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.