Group by using LINQ

Please advise how to group by a data table column name using LINQ. What is the result of it an array of data tables? Please provide a code sample?

Depending on what is defined in the linq

1 Like

which ever you have to group in colmnName write your column name.

From row In dt.AsEnumerable()
Group row By key = row(“ColumnName”) Into Group
Select Group.CopyToDataTable()

  1. From row In dt.AsEnumerable(): This part of the LINQ query converts the DataTable dt into an enumerable collection of DataRows.

  2. Group row By key = row(“ColumnName”) Into Group: This part groups the rows by the value of the “ColumnName” column. The Group keyword allows us to refer to the group of rows that have the same value in the “ColumnName” column.

  3. Select Group.CopyToDataTable(): This part selects each group and converts it into a new DataTable using the CopyToDataTable() method. This method creates a new DataTable from the rows in the group.

in VB.Net

Dim groupQuery = studentList.GroupBy(Function(s) s.Age)
        
For Each ageGroup In groupQuery
            
    Console.WriteLine("Age Group: {0}", ageGroup.Key)  //Each group has a key 
            
    For Each student In ageGroup.AsEnumerable()  //Each group has a inner collection
        Console.WriteLine("Student Name: {0}", student.StudentName)
    Next
Next

Output:
AgeGroup: 18
StudentName: John
StudentName: Bill
AgeGroup: 21
StudentName: Steve
StudentName: Abram
AgeGroup: 20
StudentName: Ram

1 Like

How can this be converted into an array of data tables? Thank you,

as mentioned to you in your other thread

instead of toList we use toArray

Getting an error here, with Groups
Definition of method “Groups” is not accessible in the context.

Typo is corrected.

However we recommend keeping this thread as it is and open a new topic if further assistance is needed

1 Like

Thank you, @ppr
The error is fixed now.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.