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

Single

Lambda Query

Single: Retrieves only element in a collection. Throws exception if not exactly one element in collection.

Single: Retrieves only element in a collection. Throws exception if not exactly one element in collection.

This Lambda Expression sample retrieves a single element from each array, but from arrays with not exactly one element it throws exception.

This Lambda Expression sample retrieves a single element from each array, but from arrays with not exactly one element it throws exception.

  • C#
  • VB.Net
  • F#
// A Query Expression cannot be constructed for Single() in C#.
// Consider using a Lambda Expression instead.
' A Query Expression cannot be constructed for Single() in VB.NET.
' Consider using a Lambda Expression instead.
// There is no Single() for Query Expressions in F#, but it has the similar "exactlyOne".
// Note: Single will throw an Exception, if there is not exactly one element in the array.
let Sample_Single_Linq() =
    let names1 = [|"Peter" |]
    let names3 = [|"Peter"; "Joe"; "Wilma"|]
    let empty:System.Object list = []

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

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

    try
        // This will throw an exception because array contains no elements
        let resultEmpty = query {
            for e in empty do
            exactlyOne
        }
        ()
    with
        | ex -> Debug.WriteLine(sprintf "%s" ex.Message)

    try
        // This will throw an exception as well because array contains more than one element
        let result3 = query {
            for n in names3 do
            exactlyOne
        }
        ()
    with
        | ex -> Debug.WriteLine(sprintf "%s" ex.Message)
Output:
The only name in the array is:
Peter
A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
Sequence contains no elements
A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
Sequence contains more than one element
  • C#
  • VB.Net
  • F#
// Note: Single will throw an Exception, if there is not exactly one element in the array.
static void Sample_Single_Lambda()
{
    string[] names1 = { "Peter" };
    string[] names3 = { "Peter", "Joe", "Wilma" };
    string[] empty = { };

    var result1 = names1.Single();

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

    try
    {
        // This will throw an exception because array contains no elements
        var resultEmpty = empty.Single();
    }
    catch (Exception e)
    {
        Debug.WriteLine(e.Message);
    }

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

    Dim result1 = names1.Single()

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

    Try
        ' This will throw an exception because array contains no elements
        Dim resultEmpty = empty.Single()
    Catch e As Exception
        Debug.WriteLine(e.Message)
    End Try

    Try
        ' This will throw an exception as well because array contains more than one element
        Dim result3 = names3.Single()
    Catch e As Exception
        Debug.WriteLine(e.Message)
    End Try
End Sub
Output:
The only name in the array is:
Peter
A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
Sequence contains no elements
A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
Sequence contains more than one element
// Note: Single will throw an Exception, if there is not exactly one element in the array.
let Sample_Single_Lambda() =
    let names1 = [|"Peter" |]
    let names3 = [|"Peter"; "Joe"; "Wilma"|]
    let empty = [| |]

    let result1 = names1.Single()

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

    try
        // This will throw an exception because array contains no elements
        let resultEmpty = empty.Single()
        ()
    with
        | ex -> Debug.WriteLine(sprintf "%s" ex.Message)

    try
        // This will throw an exception as well because array contains more than one element
        let result3 = names3.Single()
        ()
    with
        | ex -> Debug.WriteLine(sprintf "%s" ex.Message)
Output:
The only name in the array is:
Peter
A first chance exception of type 'System.InvalidOperationException' occurred in System.Core.dll
Sequence contains no elements
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