Grouping is one of the very useful features provided by LINQ, This method is often used when we have a large number of data to displayed in different group wise.
To understand, how to use group by clause in LINQ query , first we create a class called “Student”, then we create a collection object of that class, then try to use group by clause with query syntax and method syntax.
public class Student { public Student() { } public string FullName { get; set; } = "Not Set"; public int StreamId { get; set; } public int Score { get; set; } = 0; public string Subjects { get; set; } = "All"; }
Here we learn how to use Groupby in LINQ with few easy examples
Here we have created a collection object, now we use this collection object in all following group by examples
var studentsStream = new List<Student> { new Student { FullName = "Aruna", StreamId=1, Score = 10 }, new Student { FullName = "Janet", StreamId=2, Score = 9 }, new Student { FullName = "Ajay", StreamId=1, Score = 11 }, new Student { FullName = "Kunal", StreamId=2, Score = 13 }, new Student { FullName = "Chandra", StreamId=2, Score = 8 }, };
Here is an example how we can use group by clause based on single column
var groupScores = from techStream in studentsStream group techStream by techStream.StreamId into studentGroup select new { Stream = studentGroup.Key, GroupScore = studentGroup.Sum(x => x.Score), }; foreach (var scr in groupScores) { Console.WriteLine(string.Format("{0}-{1}", scr.Stream, scr.GroupScore)); }
In above code we have calculated the scrore of each group, here is the result
1 - 21 2 - 30
In above example if you notice, we have used sum function to get the sum of score, here is the piece of code again
var groupScores = from techStream in studentsStream group techStream by techStream.StreamId into studentGroup select new { Stream = studentGroup.Key, GroupScore = studentGroup.Sum(x => x.Score), };
Here is an example of using group by clause with multiple columns.
Notice, we are holding the collection into an Anonymous type variable.
// Anonymous type variable var students = from s in studentsStream group s by new { s.StreamId, s.Score } into g orderby g.Key.StreamId select new { StreamId = g.Key.StreamId, Score = g.Key.Score, TotalCount = g.Count() }; foreach (var stu in students) { Console.Write($"{stu.StreamId} : {stu.TotalCount} \n"); Console.Write("************** \n"); }
The same query also can be written this way using method syntax
In method syntax if you want to have multiple columns then put the inside
new { column1, column1}
// Anonymous type variable var students1 = studentsStream .GroupBy(s => new { s.Score, s.StreamId}) .OrderBy(g => g.Key.StreamId) .Select(g => new { StreamId = g.Key, TotalCount = g.Count() }); foreach (var stu in students1) { Console.Write($"{stu.StreamId} : {stu.TotalCount} \n"); Console.Write("************** \n"); }
Both above methods will give same result.
You may be interested in following tutorial