Linq Example 14-Group By Simple

4:53 AM
Linq Query:

//Group By

var emp1 = new { empno = 1, Department = "IT", Place="London"};
var emp2 = new { empno = 2, Department = "Computer", Place = "Paris" };
var emp3 = new { empno = 3, Department = "IT", Place = "Paris" };
var emp4 = new { empno = 4, Department = "Computer", Place = "Washington" };
var emp5 = new { empno = 5, Department = "Mechanical", Place = "Washington" };
var emp6 = new { empno = 6, Department = "Mechanical" , Place="Paris"};

var employees = new[] { emp1,emp2,emp3,emp4,emp5,emp6}; //Arrary of 6 Employees
//Finding Total Numbers of Employees in Each Department

var groups =
 from myEmp in employees
               group myEmp by myEmp.Department;

            foreach (var grp in groups)
            {
                Console.WriteLine("{0} : {1} ", grp.Key, grp.Count());
            }

            //Finding Total Numbers of Employees in Each Place
            var groups_Place =
                from myEmp in employees
                group myEmp by myEmp.Place;
            foreach (var grp in groups_Place)
            {
                Console.WriteLine("{0} : {1} ", grp.Key, grp.Count());
            }


Output For Qeury 1 :

IT : 2
Computer : 2
Mechanical : 2


Output For Qeury 2 :

London : 1
Paris : 3
Washington : 2





0 comments:

Post a Comment