Grouping Data via GroupBy in LINQ

Suppose, a there is a collection of student record where name of each student, the name of the course and the marks they have taken against each course is stored. You want to get total marks of the student in all course, how would you do this? this is where GroupBy clause is handy. It groups the data on the basis of the specified attribute. Have a look at the following example to understand this concept.

´╗┐using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpTutorials {

    public class StudentRecord {

        public string studname;
        public string coursename;
        public int marks;

        public StudentRecord(string sn, string sc, int sm) {
            this.studname = sn;
            this.coursename = sc;
            this.marks = sm;
        }
    }

    class Tutorial {
        static void Main() {
            StudentRecord sr = new StudentRecord("Mike", "Mathematics", 89);
            StudentRecord sr1 = new StudentRecord("John", "Mathematics", 45);
            StudentRecord sr2 = new StudentRecord("Sara", "Mathematics", 67);
            StudentRecord sr3 = new StudentRecord("Will", "Mathematics", 60);
            StudentRecord sr4 = new StudentRecord("Mike", "English", 91);
            StudentRecord sr5 = new StudentRecord("Sara", "English", 78);
            StudentRecord sr6 = new StudentRecord("Mike", "Science", 71);
            StudentRecord sr7 = new StudentRecord("Sara", "Science", 94);
            StudentRecord sr8 = new StudentRecord("John", "English", 78);

            List<StudentRecord> studentlist =new List<StudentRecord>();

            studentlist.Add(sr);
            studentlist.Add(sr1);
            studentlist.Add(sr2);
            studentlist.Add(sr3);
            studentlist.Add(sr4);
            studentlist.Add(sr5);
            studentlist.Add(sr6);
            studentlist.Add(sr7);
            studentlist.Add(sr8);

            var totalmarks = studentlist.GroupBy(n => n.studname).Select(g => new  {
					Name = g.Key,
					MarksTotal = g.Sum(x => x.marks)
				});

            foreach (var studentrec in totalmarks) Console.WriteLine(studentrec.Name + ":" + studentrec.MarksTotal);

            Console.ReadKey();
        }
    }
}

Download the code

The above code groups all the students by their names and then uses aggregate Sum function to calculate sum of marks in all of the courses that they have take. In the output you shall names of the students along with their total obtained marks.

<<< Linq Filtering Operators in C#Joining in LINQ >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .