ARTICLE

LINQ Distinct query operator in VB.NET

Posted by Micalgray Articles | LINQ with VB.NET March 25, 2011
Here, we will see that how to removes duplicate elements from a sequence in LinQ using VB.NET.
 
Reader Level:

Here, we will see that how to removes duplicate elements from a sequence in LinQ using VB.NET.

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()

Example1

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

Example2

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


d2.gif

Login to add your contents and source code to this article
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor