Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Create XML document in C# using LINQ XDocument Class

In this articles, I am going to explain you how to create XML document in C# using LINQ XDocument class. Below is step by step tutorial.

Namespace Required

Create an empty asp.net web application and add a webform to it.
Include below namespace.

LINQ Take and TakeWhile Partitioning operators in C#

LINQ Take and TakeWhile Partitioning operators in C#

In this article, I am going to explain you LINQ Take and TakeWhile partitioning operators in C#. I have already explained Skip and SkipWhile operators in detail. Below is the four partitioning operators. Partitioning operators split the collection into two parts and returns one part only.
1) Skip
2) SkipWhile  (click here to read about Skip and SkipWhile)
3) Take - It takes element up-to specified position starting from first element in collection or sequence.
4) TakeWhile - It take elements from given collection until the specified condition is true.

Let's understand the these operators with examples.

Using Take Partitioning Operator In LINQ

Example 1

Let's apply Take operator on a string array which contains some words. Here Take operator will Take first 4 element from collection and return.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
var takeFirstFourWords = words.Take(4);
foreach (var word in takeFirstFourWords)
{
    Console.WriteLine(word);
}
Console.ReadKey();
//OUTPUT:
//Five
//Four
//One
//Three

Example 2

Here, it will return first 5 numbers.

int[] numbers = { 9, 8, 6, 7, 2, 5, 4, 1, 3, 0 };
var takeFirstFiveNumbers = numbers.Take(5);
foreach (var number in takeFirstFiveNumbers)
{
    Console.WriteLine(number);
}
Console.ReadKey();
//OUTPUT:
//9
//8
//6
//7
//2

Example 3

Take and TakeWhile operator do not support in query syntax but still we can use Take on query variable. Consider the example given below, we need 2 words from first 4 words whose length is greater than 4.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };

var stringNumbers = from s in words
                              where s.Length > 4 // find words whose length is grater than 4
                              select s;

Console.WriteLine("words whose length is grater than 4");
foreach (var word in stringNumbers)
{
    Console.WriteLine(word);
}
/*
OUTPUT:
Three
Eight
Seven
*/

var takeFirstTwoWords = stringNumbers.Take(2); //take first 2 words
Console.WriteLine("After taking two words");
foreach (var word in takeFirstTwoWords)
{
    Console.WriteLine(word);
}
Console.ReadKey();
/*
OUTPUT:
Three
Eight
*/

Using TakeWhile Partitioning Operator In LINQ

Example 1

Let's understand TakeWhile operator with example. Consider the string array of words given below. Here first 3 elements are "Five", "Four", "One" and their length is less than 5. So, according to TakeWhile definition, for the first 3 elements condition is true because there length is less than 5, but from 4th element that is "Three" here length is equal to 5 that means if length is equal to 5 then condition becomes false, so TakeWhile will return those element for which condition was true.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
//length is               4         4         3         5           4         5          3         5           3         4
//length < 5           true     true     true     false
var data = words.TakeWhile(x => x.Length < 5);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Five
//Four
//One

Example 2

Here, we will use same example as shown above, in above example we used (<) less than operator, now we will use (>) greater than operator. Here the first element is "Five" whose length is equal to 4, but it is less than 5, so condition becomes false at first element only because we are checking for the element whose length is greater than 5. So, if condition becomes false at first statement only then it will return an empty collection.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
//length is               4         4         3         5           4         5          3         5           3         4
//length > 5           false    
var data = words.TakeWhile(x => x.Length > 5);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//No Output

Example 3

Here, in below example first 5 elements when divided by 5, they have some Remainder but from 6th element that is '5' which has Remainder 0, here the condition becomes false because we are checking for Remainder should not be equal to zero, so it will return those element for which condition was true.

int[] numbers = { 9, 8, 6, 7, 2, 5, 4, 1, 3, 0 };

var data = numbers.TakeWhile(x => x % 5 != 0);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//9
//8
//6
//7
//2

Using TakeWhile With Index

We can use, second overload of TakeWhile. It passes index of each elements. In below example, it take all the element till the length of elements is greater than it's index. Here, condition becomes false at 5th element("Nine"), so it will return elements for which condition was true.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
// length is              4         4         3         5           4         5         3         5           3         4
// index  is              0         1         2         3           4         5         6         7           8         9
// length > index   true     true     true     true       false      -         -          -            -          -
var data = words.TakeWhile((x,i) => x.Length > i);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Five
//Four
//One
//Three

LINQ Skip and SkipWhile Partitioning operators in C#

LINQ Skip and SkipWhile Partitioning operators in C#

In this article, I am going to explain you LINQ Skip and SkipWhile partitioning operators in C#. Below is the four partitioning operators in C#. Partitioning operators split the collection into two parts and returns one part only.
1) Skip - It skips element up-to specified position starting from first element in collection.
2) SkipWhile – It skip elements in the collection till the specified condition is true. It returns a new collection that includes all the remaining elements once the specified condition becomes false for any element.
3) Take 4) TakeWhile  (click here to read about Take and TakeWhile)

Let's understand the these operators with examples.

Using Skip Partitioning Operator In LINQ

Example 1

Let's apply Skip operator on a string array which contains some words. Here Skip operator will skip first 4 element from collection and returns remaining element from array.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
var skipFirstFourWords = words.Skip(4);
foreach (var word in skipFirstFourWords)
{
    Console.WriteLine(word);
}
Console.ReadKey();
//OUTPUT:
//Nine
//Eight
//Six
//Seven
//Two
//Zero

Example 2

int[] numbers = { 9, 8, 6, 7, 2, 5, 4, 1, 3, 0 };
var skipFirstFiveNumbers = numbers.Skip(5);
foreach (var number in skipFirstFiveNumbers)
{
    Console.WriteLine(number);
}
Console.ReadKey();
//OUTPUT:
//5
//4
//1
//3
//0

Example 3

Skip and SkipWhile operator do not support in query syntax but still we can use skip and skip on query variable. Consider the example given below, we need to skip 2 words from first 4 words whose length is greater than 4.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };

var stringNumbers = from s in words
                              where s.Length > 4 // find words whose length is grater than 4
                              select s;

Console.WriteLine("words whose length is grater than 4");
foreach (var word in stringNumbers)
{
    Console.WriteLine(word);
}
/*
OUTPUT:
Three
Eight
Seven
*/

var skipFirstTwoWords = stringNumbers.Skip(2); //skip first 2 words
Console.WriteLine("After skipping two words");
foreach (var word in skipFirstTwoWords)
{
    Console.WriteLine(word);
}
Console.ReadKey();
/*
OUTPUT:
Seven
*/

Example 4

In this example, we will use two List object of type Employee and Department as shown below. Here, we need to skip first 2 employees of Department 'IT' using query syntax. It is similar to Example 3.

 class Program
 {
     class Employee
     {
         public int Id { get; set; }
         public string Name { get; set; }
         public int Salary { get; set; }
         public int DeptId { get; set; }
     }
     class Department
     {
         public int Id { get; set; }
         public string Name { get; set; }
     }
     static void Main(string[] args)
     {
         // list of type Employee
         List<Employee> employee = new List<Employee>(){
             new Employee { Id=1, Name = "Rahul", Salary=50000, DeptId=101},
             new Employee { Id=2, Name = "John", Salary=10000, DeptId=102},
             new Employee { Id=3, Name = "Mike", Salary=4000, DeptId=103},
             new Employee { Id=4, Name = "Mary", Salary=75000, DeptId=101},
             new Employee { Id=5, Name = "Sachin", Salary=6500, DeptId=102},
             new Employee { Id=6, Name = "Deepak", Salary=80000, DeptId=103},
             new Employee { Id=7, Name = "Mithoon", Salary=10000, DeptId=101},
             new Employee { Id=8, Name = "Hrithik", Salary=72000, DeptId=102},
             new Employee { Id=9, Name = "Savio", Salary=10000, DeptId=103},
             new Employee { Id=10, Name = "Yogesh", Salary=90000, DeptId=101}
         };
         // list of type Department
         List<Department> department = new List<Department>(){
             new Department { Id=101, Name = "IT"},
             new Department { Id=102, Name = "HR"}, 
             new Department { Id=103, Name = "Payroll"}, 
             new Department { Id=104, Name = "Sales"}, 
             new Department { Id=105, Name = "Production"},
         };

         var data = from e in employee
                    join d in department
                    on e.DeptId equals d.Id
                    where d.Name == "IT"
                    select new
                    {
                        eId = e.Id,
                        eName = e.Name,
                        dName = d.Name
                    };
         Console.WriteLine("---------All employees in department IT---------");
         foreach (var v in data)
         {
             Console.WriteLine("Employee Id - " + v.eId + ", Employee Name - " + v.eName + ", Department Name - " + v.dName);
         }

         Console.WriteLine("---------Now skip first two employees in department IT---------");
         var afterSkip = data.Skip(2);
         foreach (var v in afterSkip)
         {
             Console.WriteLine("Employee Id - " + v.eId + ", Employee Name - " + v.eName + ", Department Name - " + v.dName);
         }
         Console.ReadKey();

         //OUTPUT:
         //---------All employees in department IT---------
         //Employee Id - 1, Employee Name - Rahul, Department Name - IT
         //Employee Id - 4, Employee Name - Mary, Department Name - IT
         //Employee Id - 7, Employee Name - Mithoon, Department Name - IT
         //Employee Id - 10, Employee Name - Yogesh, Department Name - IT
         //---------Now skip first two employees in department IT---------
         //Employee Id - 7, Employee Name - Mithoon, Department Name - IT
         //Employee Id - 10, Employee Name - Yogesh, Department Name - IT
     }
 }

Using SkipWhile Partitioning Operator In LINQ

Example 1

Let's understand SkipWhile operator with example. Consider the string array of words given below. Here first 3 elements are "Five", "Four", "One" and their length is less than 5, so according to SkipWhile definition, first 3 elements satisfy condition and condition becomes true but from 4th element that is "Three" here length is equal to 5 that means if length is equal to 5 then condition becomes false, so SkipWhile will return remaining operator once condition is false.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
//length is               4         4         3         5           4         5          3         5           3         4
//length < 5           true     true     true     false
var data = words.SkipWhile(x => x.Length < 5);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Three
//Nine
//Eight
//Six
//Seven
//Two
//Zero

Example 2

Here, we will use same example as shown above, in above example we used (<) less than operator, now we will use (>) greater than operator. Here the first element is "Five" whose length is equal to 4, but it is less than 5, so condition becomes false at first element only because we are checking for element whose length is greater than 5, so according to definition, it will returns remaining element from element where condition become false.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
//length is               4         4         3         5           4         5          3         5           3         4
//length > 5           false    
var data = words.SkipWhile(x => x.Length > 5);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Five
//Four
//One
//Three
//Nine
//Eight
//Six
//Seven
//Two
//Zero

Example 3

Here, in below example first 5 elements when divided by 5, they have some Remainder but from 6th element that is '5' which has Remainder 0, here the condition becomes false because we are checking for Remainder should not be equal to zero, so it will return all the remaining elements from 6th element.

int[] numbers = { 9, 8, 6, 7, 2, 5, 4, 1, 3, 0 };

var data = numbers.SkipWhile(x => x % 5 != 0);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//5
//4
//1
//3
//0

Using SkipWhile With Index

Example 1

We can use, second overload of SkipWhile. It passes index of each elements. In below example, it skips all the element till the length of elements is greater than it's index. Here, condition becomes false at 5th element("Nine"), so it will return remaining elements.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
// length is              4         4         3         5           4         5         3         5           3         4
// index  is              0         1         2         3           4         5         6         7           8         9
// length > index   true     true     true     true       false      -         -          -            -          -
var data = words.SkipWhile((x,i) => x.Length > i);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Nine
//Eight
//Six
//Seven
//Two
//Zero

Example 4

In this example, we will use two List object of type Employee and Department as used in Example 4 of Skip Operator. Here, we will fetch all employees of Department 'IT' using query syntax.

var data = from e in employee
           join d in department
           on e.DeptId equals d.Id
           where d.Name == "IT"
           select new
           {
               eId = e.Id,
               eName = e.Name,
               dName = d.Name
           };
Console.WriteLine("---------All employees in department IT---------");
foreach (var v in data)
{
    Console.WriteLine("Employee Id - " + v.eId + ", Employee Name - " + v.eName + ", Department Name - " + v.dName);
}
//OUTPUT:
//---------All employees in department IT---------
//Employee Id - 1, Employee Name - Rahul, Department Name - IT
//Employee Id - 4, Employee Name - Mary, Department Name - IT
//Employee Id - 7, Employee Name - Mithoon, Department Name - IT
//Employee Id - 10, Employee Name - Yogesh, Department Name - IT

Now, we will apply SkipWhile operator on Name column whose length is greater than 4. Here in above output Employee Name - Rahul , Rahul has length greater than 4, so condition is true here, but for Mary length is not greater than 4, so condition becomes false here.

Console.WriteLine("---------Now use SkipWhile on Name column---------");
var afterSkipWhile = data.SkipWhile(x => x.eName.Length > 4);
foreach (var v in afterSkipWhile)
{
    Console.WriteLine("Employee Id - " + v.eId + ", Employee Name - " + v.eName + ", Department Name - " + v.dName);
}
Console.ReadKey();
//---------Now use SkipWhile on Name column---------
//Employee Id - 4, Employee Name - Mary, Department Name - IT
//Employee Id - 7, Employee Name - Mithoon, Department Name - IT
//Employee Id - 10, Employee Name - Yogesh, Department Name - IT

LINQ Quantifier Operators - any, all and contains with examples in C#

LINQ Quantifier Operators - any, all and contains with examples in C#

In this article, I am going to explain you LINQ Quantifier operators in C#. Quantifier operators return boolean value i.e. true or false when some or all the elements within a sequence satisfy the conditions. Below are the 3 types of quantifier operators.
Any - It is used to check whether any elements in a sequence satisfy a condition.
All – It is used to check whether all the elements in a sequence satisfy a condition.
Contains - It is used to check whether a sequence contains a specified element.

Let's understand the these operators with examples. I have created a string array which contains random words and created two list of type Employee and Department as shown below.

class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }
    public int DeptId { get; set; }
}
class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // string array
        string[] words = { "believe", "relief", "receipt", "field" };

        // list of type Employee
        List<Employee> employee = new List<Employee>(){
                new Employee { Id=1, Name = "Rahul", Salary=50000, DeptId=101},
                new Employee { Id=2, Name = "John", Salary=10000, DeptId=102},
                new Employee { Id=3, Name = "Mike", Salary=4000, DeptId=103},
                new Employee { Id=4, Name = "Mary", Salary=75000, DeptId=101},
                new Employee { Id=5, Name = "Sachin", Salary=6500, DeptId=102},
                new Employee { Id=6, Name = "Deepak", Salary=80000, DeptId=103},
                new Employee { Id=7, Name = "Mithoon", Salary=10000, DeptId=101},
                new Employee { Id=8, Name = "Hrithik", Salary=72000, DeptId=102},
                new Employee { Id=9, Name = "Savio", Salary=10000, DeptId=103},
                new Employee { Id=10, Name = "Yogesh", Salary=90000, DeptId=101}
            };
        // list of type Department
        List<Department> department = new List<Department>(){
                new Department { Id=101, Name = "IT"},
                new Department { Id=102, Name = "HR"}, 
                new Department { Id=103, Name = "Payroll"}, 
                new Department { Id=104, Name = "Sales"}, 
                new Department { Id=105, Name = "Production"},
            };
    }
}

Using Any Quantifier Operator In LINQ

Example 1

This example uses 'any' operator to check whether the any word within array contains sub-string 'ei'.

bool flag = words.Any(w => w.Contains("ei"));
if (flag)
{
    Console.WriteLine("There is a word containing 'ei'.");
}
else
{
    Console.WriteLine("There is no word that containing 'ei'.");
}
Console.ReadKey();

/*
OUTPUT:
There is a word containing 'ei'
*/

Example 2

This example uses 'any' operator to check any word having length greater than 6.

bool flag  = words.Any(w => w.Length > 6);
if (flag)
{
    Console.WriteLine("There is a word having lengh greater than 6.");
}
else
{
    Console.WriteLine("There is no word having lengh greater than 6.");
}
Console.ReadKey();

/*
OUTPUT:
There is a word having lengh greater than 6.
*/

Example 3

This example uses 'any' operator to list the departments that do not have employees.

var data = from dp in department
           where !employee.Any(e => e.DeptId == dp.Id)
           select new { dId = dp.Id, dNane = dp.Name }; // projecting into anonymous type
foreach (var d in data)
{
    Console.WriteLine("Dept Id - " + d.dId + ", Dept Name - " + d.dNane);

}
Console.ReadKey();

/*
OUTPUT:
    Dept Id - 104, Dept Name - Sales
    Dept Id - 105, Dept Name - Production
*/

Using All Quantifier Operator In LINQ

Example 1

This example uses 'all' operator to check whether all words within array contains a letter 'e'.

bool flag = words.All(w => w.Contains("e"));
if (flag)
{
    Console.WriteLine("All the words contain letter 'e'.");
}
else
{
    Console.WriteLine("All the word do not contain letter 'e'.");
}
Console.ReadKey();

/*
OUTPUT:
    All the words contain letter 'e'.
*/

Example 2

This example uses 'all' operator to check whether all the employees name starts with a letter 'Y'.

bool flag = employee.All(e => e.Name.StartsWith("Y"));
if (flag)
{
    Console.WriteLine("All the employees Name starts with 'Y'.");
}
else
{
    Console.WriteLine("Not all employees Name starts with 'Y'.");
}

Console.ReadLine();
/*
OUTPUT:
  Not all employees Name starts with 'Y'.
*/

Using Contains Quantifier Operator In LINQ

Example 1

This example uses 'contains' operator to list down all the department having employees name starts with 'M'.

var data = department.Where(d => employee.Where(e => e.Name.StartsWith("M")).
    Select(e1 => e1.DeptId).Contains(d.Id));
 
Console.WriteLine("List of Departments having Employee Names starting with 'M'.");
foreach (var d in data)
{
    Console.WriteLine("Dept Id - " + d.Id + ", Dept Name - " + d.Name);
}
Console.ReadLine();
/*
OUTPUT:
  List of Departments having Employee Names starting with 'M'.
  Dept Id - 101, Dept Name - IT
  Dept Id - 103, Dept Name - Payroll
*/

LINQ Grouping Operator: GroupBy in C#

LINQ Grouping Operator: GroupBy in C#

In this articles, we are going to learn LINQ GroupBy operator in C#. The GroupBy operator is same as that of group by clause in SQL. GroupBy operator takes a flat sequence of items, organize that sequence into groups (IGrouping<TKey,TSource>) based on specific key and returns group of sequences. In short, GroupBy operator returns a group of elements from the given collection based on some key value. Each group is represented by (IGrouping<TKey,TSource>) object.

Related Articles

  1. Introduction to LINQ Standard Query Operators Vs SQL
  2. LINQ Ordering (Sorting) Operators: OrderBy and OrderByDescending in C#
  3. LINQ Ordering (Sorting) Operators: ThenBy, ThenByDescending and Reverse in C#

Using GroupBy Method

To understand this, I have created a Employee class with 4 public properties and one static method which will return a list of all employees as shown below

class Employee
{
   public int Id;
   public string Name;
   public int DeptId;
   public string Gender;
 
   public static List<Employee> GetAllEmployees()
   {
      Employee emp1 = new Employee { Id = 1, Name = "Rahul", Gender = "Male", DeptId = 102 };
      Employee emp2 = new Employee { Id = 2, Name = "Vijay", Gender = "Male", DeptId = 101 };
      Employee emp3 = new Employee { Id = 3, Name = "Pooja", Gender = "Female", DeptId = 102 };
      Employee emp4 = new Employee { Id = 4, Name = "Mithun", Gender = "Male", DeptId = 103 };
      Employee emp5 = new Employee { Id = 5, Name = "Mary", Gender = "Female", DeptId = 101 };
      Employee emp6 = new Employee { Id = 6, Name = "Mathew", Gender = "Male", DeptId = 101 };
      Employee emp7 = new Employee { Id = 7, Name = "John", Gender = "Male", DeptId = 103 };
      Employee emp8 = new Employee { Id = 8, Name = "Sachin", Gender = "Male", DeptId = 102 };
 
      List<Employee> empList = new List<Employee>();
 
      empList.Add(emp1);
      empList.Add(emp2);
      empList.Add(emp3);
      empList.Add(emp4);
      empList.Add(emp5);
      empList.Add(emp6);
      empList.Add(emp7);
      empList.Add(emp8);
 
      return empList;
   }
}

The following example creates a groups of employees who have same department id. Employees of the same department id will be in the same collection and each grouped collection will have a key and inner collection, where the key will be the department id and the inner collection will include employees whose department id is matched with a key.

static void Main(string[] args)
{
   var groupByResult = Employee.GetAllEmployees().GroupBy(x => x.DeptId);

   foreach (var group in groupByResult)
   {
      //Each group has a key 
      Console.WriteLine("Dept Id Group: " + group.Key);

      //Each group has a inner collection 
      foreach (var e in group)
      {
          Console.WriteLine("Id: " + e.Id + " Name: " + e.Name + " Gender: " + e.Gender + " DeptId: " + e.DeptId);
      }
      Console.WriteLine();
   }
   Console.ReadKey();
}

Below is the output.

Dept Id Group: 102
Id: 1 Name: Rahul   Gender: Male   Deptld: 102 
Id: 3 Name: Pooja   Gender: Female Deptld: 102 
Id: 8 Name: Sachin  Gender: Male   Deptld: 102
Dept Id Group: 101
Id: 2 Name: Vijay   Gender: Male   Deptld: 101 
Id: 5 Name: Mary    Gender: Female Deptld: 101 
Id: 6 Name: Mathew  Gender: Male   Deptld: 101
Dept Id Group: 103
Id: 4 Name: Mithun  Gender: Male   Deptld: 103 
Id: 7 Name: John    Gender: Male   Deptld: 103

Same thing can be achieved by using groupby SQL syntax.

static void Main(string[] args)
{
   var groupByResult = from e in Employee.GetAllEmployees()
                                group e by e.DeptId;

   foreach (var group in groupByResult)
   {
      //Each group has a key 
      Console.WriteLine("DeptId Group: " + group.Key);
      
      //Each group has a inner collection 
      foreach (var e in group)
      {
          Console.WriteLine("Id: " + e.Id + " Name: " + e.Name + " Gender: " + e.Gender + " DeptId: " + e.DeptId);
      }
      Console.WriteLine();
   }
   Console.ReadKey();
}

Using GroupBy With Aggregate Function

We can use aggregate function like Count, Min, Max, Sum, Average with GroupBy as shown below.

static void Main(string[] args)
{
   var groupByResult = Employee.GetAllEmployees().GroupBy(x => x.DeptId);

   foreach (var group in groupByResult)
   {
     Console.WriteLine("Dept Id: " + group.Key + " Employees Count: " + group.Count());
     Console.WriteLine("Dept Id: " + group.Key + " Female Employees: " + group.Count(x => x.Gender == "Female"));
     Console.WriteLine("Dept Id: " + group.Key + " Male Employees: " + group.Count(x => x.Gender == "Male"));
     Console.WriteLine("Dept Id: " + group.Key + " Min of Dept Id: " + group.Min(x => x.Id));
     Console.WriteLine("Dept Id: " + group.Key + " Max of Dept Id:  " + group.Max(x => x.Id));
     Console.WriteLine();
   }
   Console.ReadKey();
}

Below is the output.

Dept Id    : 102 Employees Count:  3
Dept Id    : 102 Female Employees: 1
Dept Id    : 102 Male Employees:   2
Dept Id    : 102 Min of Dept Id:   1
Dept Id    : 102 Max of Dept Id:   8

Dept Id    : 101 Employees Count:  3
Dept Id    : 101 Female Employees: 1
Dept Id    : 101 Male Employees:   2
Dept Id    : 101 Min of Dept Id:   2
Dept Id    : 101 Max of Dept Id:   6

Dept Id    : 103 Employees Count:  2
Dept Id    : 103 Female Employees: 0
Dept Id    : 103 Male Employees:   2
Dept Id    : 103 Min of Dept Id:   4
Dept Id    : 103 Min of Dept Id:   7

Using GroupBy With OrderBy To Sort Key Value

You can see in above example where Dept Id (which is key) is not sorted in any order. We can use OrderBy with GroupBy to sort Key value in ascending order. First, we need to project into new group then sort key using orderby keyword and to select create anonymous type.

static void Main(string[] args)
{
  var groupByResult = from e in Employee.GetAllEmployees()
                              group e by e.DeptId into newGroup // projecting into new group
                              orderby newGroup.Key  // ordering by key i.e. DeptId
                select new  // creating anonymous type
    {
     Key = newGroup.Key,
     EMP = newGroup
    };

  foreach (var group in groupByResult)
  {
      Console.WriteLine("Dept: " + group.Key + " Count: " + group.EMP.Count());

      foreach (var e in group.EMP)
      {
          Console.WriteLine("Name: " + e.Name);
      }
      Console.WriteLine();
  }
  Console.ReadKey();
}

Below is the output.

Dept: 101 Count: 3 
Name: Vijay 
Name: Mary 
Name: Mathew 

Dept: 102 Count: 3 
Name: Rahul 
Name: Pooja 
Name: Sachin 

Dept: 103 Count: 2 
Name: Mithun 
Name: John

As you can see from above output Dept Id is sorted in ascending order but the Name field is not sorted. Now, we will sort the Name field as well.

static void Main(string[] args)
{
  var groupByResult = from e in Employee.GetAllEmployees()
                              group e by e.DeptId into newGroup // projecting into new group
                              orderby newGroup.Key  // ordering by key i.e. DeptId
                select new  // creating anonymous type
    {
     Key = newGroup.Key,
     EMP = newGroup.OrderBy(x => x.Name) // sort Name using order by 
    };

  foreach (var group in groupByResult)
  {
      Console.WriteLine("Dept: " + group.Key + " Count: " + group.EMP.Count());

      foreach (var e in group.EMP)
      {
          Console.WriteLine("Name: " + e.Name);
      }
      Console.WriteLine();
  }
  Console.ReadKey();
}

Below is the output. You can see the Name field is sorted in ascending order.

Dept: 101 Count: 3
Name: Mathew
Name: Mary
Name: Vijay 

Dept: 102 Count: 3
Name: Pooja
Name: Sachin
Name: Rahul

Dept: 103 Count: 2
Name: John
Name: Mithun 

Using GroupBy With Multiple Keys

In above example, we have used only a single key that is DeptId for grouping purpose. Now we will be using three keys (DeptId, Gender and Name) to group the collection. Here is the code. If you want to learn OrderBy and ThenBy, use above link in Related Articles.

var groupByResult = Employee.GetAllEmployees()
                   .GroupBy(x => new { x.DeptId, x.Gender }) // group by using DeptId and Gender
                   .OrderBy(g => g.Key.DeptId).ThenBy(g => g.Key.Gender) // first order by on DeptId and ThenBy on Gender
                   .Select(g => new // creating anonymous type
                   {
                       Dept = g.Key.DeptId,
                       Gender = g.Key.Gender,
                       EMP = g.OrderBy(x => x.Name) // again sorting Name is ascending order
                   });

foreach (var group in groupByResult)
{
    Console.WriteLine("Dept Id: " + group.Dept + " Gender: " + group.Gender + " Count: " + group.EMP.Count());
    Console.WriteLine("-----------------------------------");
    foreach (var g in group.EMP)
    {
        Console.WriteLine(g.Name + "\t" + g.Gender + "\t" + g.DeptId);
    }
    Console.WriteLine(); Console.WriteLine();
}
Console.ReadKey();

Below is the output. As you can see first DeptId is sorted then Gender is sorted then Name is sorted in ascending order.

Dept Id: 101 Gender: Male Count: 2 
-----------------------------------
Mathew  Male 101
Vijay   Male 101


Dept Id: 102 Gender: Female Count: 1
-----------------------------------
Pooja   Female 102


Dept Id: 102 Gender: Male Count: 2 
-----------------------------------
Rahul   Male 102
Sachin  Male 102


Dept Id: 103 Gender: Male Count: 2
-----------------------------------
John    Male 103
Mithun  Male 103

Same thing can be achieved using sql like syntax.

var groupByResult = from emp in Employee.GetAllEmployees()
                            group emp by new { emp.DeptId, emp.Gender } into newGroup
                            orderby newGroup.Key.DeptId, newGroup.Key.Gender
                            select new
                               {
                                 Dept = newGroup.Key.DeptId,
                                 Gender = newGroup.Key.Gender,
                                 EMP = newGroup.OrderBy(x => x.Name)
                               };


foreach (var group in groupByResult)
{
    Console.WriteLine("Dept Id: " + group.Dept + " Gender: " + group.Gender + " Count: " + group.EMP.Count());
    Console.WriteLine("----------------------");
    foreach (var g in group.EMP)
    {
        Console.WriteLine(g.Name + "\t" + g.Gender + "\t" + g.DeptId);
    }
    Console.WriteLine(); Console.WriteLine();
}
Console.ReadKey();

Grouping Based on First Character of string

Example 1

Here, we will group Name field based on first character of the Name.

static void Main(string[] args)
{
    var groupByResult = from e in Employee.GetAllEmployees()
                                group e by e.Name[0] into newGroup  // here First Letter of the Name is Key
                                select new 
                         {
               Name = newGroup.Key,
               EMP = newGroup 
                         };
    
    foreach (var group in groupByResult)
    {
        Console.WriteLine("Name that start with the character '{0}':", group.Name);
        foreach (var w in group.EMP)
        {
            Console.WriteLine(w.Name);
        }
        Console.WriteLine();
    }
    Console.ReadKey();
}

Output is shown below.

Name that start with the character 'R'
Rahul 

Name that start with the character 'V'
Vijay 

Name that start with the character 'P'
Pooja 

Name that start with the character 'M'
Mithun 
Mary 
Mathew 

Name that start with the character 'J'
John 

Name that start with the character 'S'
Sachin 

Example 2

static void Main(string[] args)
{
   string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple",
                        "cheese", "elephant", "umbrella", "anteater" };

   var groupByResult = from w in words
                               group w by w[0] into newGroup
                               where (newGroup.Key == 'a' || newGroup.Key == 'e' || newGroup.Key == 'i'
                               || newGroup.Key == 'o' || newGroup.Key == 'u')
                               select newGroup;

   foreach (var group in groupByResult)
   {
       Console.WriteLine("Groups that start with a vowel: " + group.Key);
       foreach (var w in group)
       {
           Console.WriteLine(w);
       }
       Console.WriteLine();
   }
   Console.ReadKey();
}

Output is shown below.

Groups that start with a vowel: a
abacus
apple
anteater

Groups that start with a vowel: e
elephant

Groups that start with a vowel: u
umbrella