LINQ C# Book

Input: IEnumerable
Optional lambda expression: TSource => bool
To avoid an exception, Single requires exactly one matching element;
SingleOrDefault requires one or zero matching elements:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
int v = numbers.Single(n => n % 3 == 0);
v = numbers.Single(n => n % 2 == 0);
Console.WriteLine(v);
v = numbers.Single(n => n > 10);
v = numbers.SingleOrDefault(n => n > 10);
v = numbers.SingleOrDefault(n => n % 2 == 0);
Console.WriteLine(v);
}
}
The output:
Unhandled Exception: System.InvalidOperationException: Sequence contains more than one matching element
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
at Program.Main() in c:\g\Program.cs:line 13