×

VB.Net Programs

VB.Net program to demonstrate the GroupBy() LINQ extension method

By Nidhi Last Updated : November 11, 2024

VB.Net – GroupBy() LINQ Extension Method

In this program, we will use GroupBy() LINQ extension method to get employee records based on groups and then print those records on the console screen.

Program/Source Code:

The source code to demonstrate the GroupBy() LINQ extension method is given below. The given program is compiled and executed successfully.

VB.Net code to demonstrate the example of GroupBy() LINQ extension method

'VB.NET program to demonstrate the 
'GroupBy() LINQ extension method.

Imports System
Imports System.IO
Imports System.Linq

Module Module1
    Public Class Employee
        Public id As Integer
        Public name As String
        Public age As Integer
    End Class

    Sub Main()
        Dim empList = New List(Of Employee) From
        {
            New Employee() With {.id = 101, .name = "Amit", .age = 21},
            New Employee() With {.id = 102, .name = "Arun", .age = 22},
            New Employee() With {.id = 103, .name = "Aman", .age = 23},
            New Employee() With {.id = 104, .name = "Amar", .age = 21},
            New Employee() With {.id = 105, .name = "Akki", .age = 22},
            New Employee() With {.id = 105, .name = "Anuj", .age = 23}
        }

        Dim Emps = empList.GroupBy(Function(e) e.age)

        For Each emp In Emps
            Console.WriteLine("Age Group: {0}", emp.Key)

            For Each e In emp.AsEnumerable()
                Console.WriteLine(vbTab & "Employee Name: {0}", e.name)
            Next
        Next
    End Sub
End Module

Output

Age Group: 21
        Employee Name: Amit
        Employee Name: Amar
Age Group: 22
        Employee Name: Arun
        Employee Name: Akki
Age Group: 23
        Employee Name: Aman
        Employee Name: Anuj
Press any key to continue . . .

Explanation

In the above program, we created a module Module1 that contains a class Employee and the Main() function. The Main() function is the entry point for the program.

The Employee class contains data member "id", "name" and "age". In the Main() function, we created the list of employees. Here, we used GroupBy() LINQ extension method to group employee records based on their age and then print those employee records on the console screen.

VB.Net LINQ Query Programs »


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.