Last and Except operator in LINQ using VB.NET

Here we will see how to use Last and Except Operator in Linq.
  • 3638

Last operator

The Last operator returns the last element from a sequence.

To find last element from a sequence

Dim numbers As Integer() = {1, 2, 3, 4, 5}

Dim last As Integer = numbers.Last()

To find last element with the condition

Dim numbers As Integer() = {1, 2, 3, 4, 5}

Dim lastEven As Integer = numbers.Last(Function(n) n Mod 2 = 0

For example

This example defines the last operator in LinQ.

Module Module1

    Sub Main()

        Dim numbers As Integer() = {1, 2, 3, 4, 5}

        Dim last As Integer = numbers.Last()

        Dim lastEven As Integer = numbers.Last(Function(n) n Mod 2 = 0)

        Console.WriteLine(last)

        Console.WriteLine(lastEven)

    End Sub

End Module

OUTPUT

last.gif
 

Except operator

The Except operator produces the set difference between two sequences. It will only return elements in the first sequence that don't appear in the second.

For example

Module Module1

    Sub Main()

        Dim s1 As Integer() = {1, 2, 3, 4, 5, 6}

        Dim s2 As Integer() = {3, 4, 5, 6, 7, 8}

        Dim difference1 As IEnumerable(Of Integer) = s1.Except(s2)

        Dim difference2 As IEnumerable(Of Integer) = s2.Except(s1)

        For Each i As Integer In difference1

            Console.WriteLine(i)

        Next

        For Each i As Integer In difference2

            Console.WriteLine(i)

        Next

    End Sub

End Module

OUTPUT

except.gif

Categories

More Articles

© 2018 DotNetHeaven. All rights reserved.