LINQSamples.com
  • Samples
  • Tutorials
  • About
  • Links
  • Contact
LINQ to Objects

Aggregation

Aggregate, Average, Count, LongCount, Max, Min, Sum

      Aggregate (simple)       Aggregate (seed)       Average       Count       LongCount       Max       Min       Sum

Conversion

AsEnumerable, Cast, OfType, ToArray, ToDictionary, ToList, ToLookup

      AsEnumerable       Cast       OfType       ToArray       ToDictionary (simple)       ToDictionary (conditional)       ToList       ToLookup

Element

ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault

      ElementAt       ElementAtOrDefault       First (simple)       First (conditional)       FirstOrDefault       Last       LastOrDefault (simple)       LastOrDefault (conditional)       Single       SingleOrDefault

Generation

DefaultIfEmpty, Empty, Range, Repeat

      DefaultIfEmpty (simple)       DefaultIfEmpty (default value)       Empty       Range       Repeat

Grouping

GroupBy

      GroupBy

Join

GroupJoin, Join

      GroupJoin (left outer join)       Join (inner join)

Ordering

OrderBy, OrderByDescending, Reverse, ThenBy, ThenByDescending

      OrderBy (simple - numbers)       OrderBy (simple - dates)       OrderBy (simple - objects)       OrderByDescending       Reverse       ThenBy       ThenByDescending

Other

Concat, SequenceEqual, Zip

      Concat (simple - numbers)       Concat (simple - strings)       SequenceEqual       Zip

Partitioning

Skip, SkipWhile, Take, TakeWhile

      Skip       SkipWhile       Take       TakeWhile

Projection

Select, SelectMany

      Select (simple)       Select (anonymous type)       Select (indexed)       SelectMany (cross join)

Quantifiers

All, Any, Contains

      All       Any       Contains

Restriction

Where

      Where (simple - numbers)       Where (simple - objects)       Where (indexed)

Set

Distinct, Except, Intersect, Union

      Distinct       Except       Intersect       Union
  Close

SingleOrDefault

Lambda Query

SingleOrDefault: Retrieves only element in a collection, or default value if collection is empty.

SingleOrDefault: Retrieves only element in a collection, or default value if collection is empty.

This Lambda Expression sample retrives a single element from array, but from arrays with not exactly one element it gets default value (null).

This Lambda Expression sample retrives a single element from array, but from arrays with not exactly one element it gets default value (null).

  • C#
  • VB.Net
  • F#
// A Query Expression cannot be constructed for SingleOrDefault() in C#.
// Consider using a Lambda Expression instead.
' A Query Expression cannot be constructed for SingleOrDefault() in VB.NET.
' Consider using a Lambda Expression instead.
// There is no SingleOrDefault() for Query Expressions in F#, but it has the similar "exactlyOneOrDefault".
let Sample_SingleOrDefault_Linq() =
    let names1 = [| "Peter" |]
    let names3 = [| "Peter"; "Joe"; "Wilma" |]
    let empty:System.String list = []

    let result1 = query {
        for n in names1 do
        exactlyOneOrDefault
    }

    let resultEmpty = query {
        for n in empty do
        exactlyOneOrDefault
    }
    
    Debug.WriteLine(sprintf "The only name in the array is:")
    Debug.WriteLine(sprintf "%s" result1)

    Debug.WriteLine(sprintf "As array is empty, exactlyOneOrDefault yields null:")
    Debug.WriteLine(sprintf "%b" (resultEmpty = null))

    try
        // This will throw an exception as well because array contains more than one element
        let result3 = query {
            for n in names3 do
            exactlyOneOrDefault
        }
        ()
    with
        | e -> Debug.WriteLine(sprintf "%s" e.Message)
Output:
The only name in the array is:
Peter
As array is empty, exactlyOneOrDefault yields null:
true
A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
Sequence contains more than one element
  • C#
  • VB.Net
  • F#
// Note: SingleOrDefault retrieves null value if array is empty, and...
//       ...throws an exception if array contains more than one element.
static void Sample_SingleOrDefault_Lambda()
{
    string[] names1 = { "Peter" };
    string[] names3 = { "Peter", "Joe", "Wilma" };
    string[] empty = { };

    var result1 = names1.SingleOrDefault();

    var resultEmpty = empty.SingleOrDefault();

    Debug.WriteLine("The only name in the array is:");
    Debug.WriteLine(result1);

    Debug.WriteLine("As array is empty, SingleOrDefault yields null:");
    Debug.WriteLine(resultEmpty == null);

    try
    {
        // This will throw an exception as well because array contains more than one element
        var result3 = names3.SingleOrDefault();
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
    }
}
Output:
The only name in the array is:
Peter
As array is empty, SingleOrDefault yields null:
True
A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
Sequence contains more than one element
' Note: SingleOrDefault retrieves null value if array is empty, and...
'       ...throws an exception if array contains more than one element.
Private Shared Sub Sample_SingleOrDefault_Lambda()
    Dim names1 As String() = {"Peter"}
    Dim names3 As String() = {"Peter", "Joe", "Wilma"}
    Dim empty As String() = {}

    Dim result1 = names1.SingleOrDefault()

    Dim resultEmpty = empty.SingleOrDefault()

    Debug.WriteLine("The only name in the array is:")
    Debug.WriteLine(result1)

    Debug.WriteLine("As array is empty, SingleOrDefault yields null:")
    Debug.WriteLine(resultEmpty Is Nothing)

    Try
        ' This will throw an exception as well because array contains more than one element
        Dim result3 = names3.SingleOrDefault()
    Catch e As Exception
        Debug.WriteLine(e.Message)
    End Try
End Sub
Output:
The only name in the array is:
Peter
As array is empty, SingleOrDefault yields null:
True
A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
Sequence contains more than one element
let Sample_SingleOrDefault_Lambda() =
    let names1 = [| "Peter" |]
    let names3 = [| "Peter"; "Joe"; "Wilma" |]
    let empty:System.String list = []

    let result1 = names1.SingleOrDefault()

    let resultEmpty = empty.SingleOrDefault()

    Debug.WriteLine(sprintf "The only name in the array is:")
    Debug.WriteLine(sprintf "%s" result1)

    Debug.WriteLine(sprintf "As array is empty, SingleOrDefault yields null:")
    Debug.WriteLine(sprintf "%b" (resultEmpty = null))

    try
        // This will throw an exception as well because array contains more than one element
        let result3 = names3.SingleOrDefault()
        ()
    with
        | e -> Debug.WriteLine(sprintf "%s" e.Message)
Output:
The only name in the array is:
Peter
As array is empty, SingleOrDefault yields null:
true
A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
Sequence contains more than one element

Share this sample on:

© 2023 - LINQSamples.com | Terms Of Service  -  Privacy Policy