Distinct query operator in LINQ using VB.NET

Here we will see that how to removes duplicate elements from a sequence in Linq using VB.NET.
  • 12006

Distinct operator

The Distinct operator eliminates duplicate elements from a sequence or this operator defines the unique elements from a sequence.      

Understanding Distinct

The below defines the names can be an array of numbers, strings,or even objects. 

Here is an example of names.

Dim names As String() = New String() {"Ram", "Paul", "Ram", "hari", "Paul", "hari", "Janet"}

The select syntax in LINQ is similar to select clause of SQL. 

Here is a simple select. 

Dim q As IEnumerable(Of String) = From s In names Select s

In the above statement, I select n in names. 
Now using Distinct operator

For Each s As [String] In q.Distinct()

Example 1

The below code removes duplicate elements from a sequence in LinQ using VB.NET
 

Module Module1

    Public Sub Main()

        Dim names As String() = New String() {"Ram", "Paul", "Ram", "hari", "Paul", "hari", "Janet"}

        Dim q As IEnumerable(Of String) = From s In names Select s

        For Each s As [String] In q.Distinct()

            Console.WriteLine(s)

        Next

    End Sub

End Module

OUTPUT

d3.gif

Example 2

The below code removes duplicate character from RohatashKumar in LinQ using VB.NET.

Module Module1

    Public Sub Main()

        Dim distinctLetters As Char() = "Rohatashkumar".Distinct().ToArray()

        Dim s As New String(distinctLetters)

        Console.WriteLine(s)

    End Sub

End Module

 

OUTPUT
 

d4.gif

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.