How Grouping working in Linq

Copy paste the code as it is in a blank page with ConsoleApplication1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var employeeGroup = from employee in Employee.GetAllEmployees()
group employee by employee.Department;

foreach (var group in employeeGroup)
{
Console.WriteLine("{0} - {1}", group.Key, group.Count());
Console.WriteLine("----------");
foreach (var employee in group)
{
Console.WriteLine(employee.Name + "\t" + employee.Department);
}

}
Console.WriteLine(); Console.WriteLine();
}
}

public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string Department { get; set; }
public int Salary { get; set; }

public static List GetAllEmployees()
{
return new List()
{
new Employee { ID = 1, Name = "Mark", Gender = "Male",
Department = "IT", Salary = 45000 },
new Employee { ID = 2, Name = "Steve", Gender = "Male",
Department = "HR", Salary = 55000 },
new Employee { ID = 3, Name = "Ben", Gender = "Male",
Department = "IT", Salary = 65000 },
new Employee { ID = 4, Name = "Philip", Gender = "Male",
Department = "IT", Salary = 55000 },
new Employee { ID = 5, Name = "Mary", Gender = "Female",
Department = "HR", Salary = 48000 },
new Employee { ID = 6, Name = "Valarie", Gender = "Female",
Department = "HR", Salary = 70000 },
new Employee { ID = 7, Name = "John", Gender = "Male",
Department = "IT", Salary = 64000 },
new Employee { ID = 8, Name = "Pam", Gender = "Female",
Department = "IT", Salary = 54000 },
new Employee { ID = 9, Name = "Stacey", Gender = "Female",
Department = "HR", Salary = 84000 },
new Employee { ID = 10, Name = "Andy", Gender = "Male",
Department = "IT", Salary = 36000 }
};
}
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s