Zip operator in Linq using VB.NET

This article demonstrates how to use the Zip operator to merge two sequences.
  • 4066

Introduction

The Zip operator is the part of .Net framework 4.0. The Zip operator combines two collections into a single collection. The combines happens in the function. It takes two arguments (the element from first source, and the element from the second source) and lets you return a combined type.

Understanding Zip

We take two collections. The first collection is collection of array of numbers.

Dim First As Integer() = {1, 2, 3}

The second collection is collection of array of strings.

Using Zip operator

Now using Zip operator to merge two collections into a single collection.

Dim zip As IEnumerable(Of String) = First.Zip(Second, Function(n, w) Convert.ToString(n) & "=" & Convert.ToString(w))

        For Each i As String In zip

            Console.WriteLine(i)

        Next

 

Example 1

Module Module1

    Sub Main()

        Dim First As Integer() = {1, 2, 3}

        Dim second As String() = {"one", "two", "three", "four"}

        Dim zip As IEnumerable(Of String) = First.Zip(Second, Function(n, w) Convert.ToString(n) & "=" & Convert.ToString(w))

        For Each i As String In zip

            Console.WriteLine(i)

        Next

    End Sub

End Module

OUTPUT

Zip-operator.gif
 

Example 2

Module Module1

    Sub Main()

        Dim names As String() = {"Rohatash Kumar"}

        Dim ages As Integer() = {24, 60}

        Dim result As IEnumerable(Of String) = names.Zip(ages, Function(name, age) Convert.ToString(name) & " is " & Convert.ToString(age) & " years old.")

        For Each i As String In result

            Console.WriteLine(i)

        Next

    End Sub

End Module

 

OUTPUT

Zip-operator1.gif

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.