Distinct and ElementAt operator in Linq using VB.NET

This article defines the basic use of the Distinct and ElementAt operator in LINQ.
  • 3597

Distinct operator

The Distinct operator is used to eliminate duplicate elements from a sequence.

The below defines the names is an array of string or even objects. Here is an example of names.

Dim names As String() = {"Rohatash", "Monu", "Ajay", "Vijay", "Ram", "Hari", "vikash", "Ram", "Vijay", "Rohatash"}

Using Distinct operator

Distinct operator eliminate duplicate elements from above sequence.

Dim q = (From s In names).Distinct()

For Each name As [String] In q

Console.WriteLine(name)

 Next

For example

This example remove the duplicate name from the sequence.

Module Module1

    Sub Main()

       Dim names As String() = {"Rohatash", "Monu", "Ajay", "Vijay", "Ram", "Hari", "vikash", "Ram", "Vijay", "Rohatash"}

        Dim q = (From s In names).Distinct()

        For Each name As [String] In q

            Console.WriteLine(name)

        Next

    End Sub

End Module

 

OUTPUT
 

didtinct.gif
 

ElementAt operator

 

The ElementAt operator returns the element at a given index in a sequence.

 

For example

 

The below example defines The ElementAt operator that returns the element at index 2 in a sequence.

 

Module Module1

    Sub Main()

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

        Dim third As Integer = numbers.ElementAt(2)

        Console.WriteLine("The element at index 2 is :" & third)

    End Sub

End Module

 

OUTPUT
 

ea.gif

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.