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

LINQ Ordering (Sorting) Operators: ThenBy, ThenByDescending and Reverse in C#

In the previous tutorial, I explained OrderBy and OrderByDescending in C# with examples. In this tutorial, we are going to learn ThenBy, ThenByDescending and Reverse operators in C#. LINQ sorting operators are used to arrange the collection data into ascending or descending order based on one or more attributes (fields).

Below are the five sorting operator.
1. OrderBy
2. OrderByDescending
3. ThenBy
4. ThenByDescending
5. Reverse

Related Articles

  1. Introduction to LINQ Standard Query Operators Vs SQL

ThenBy

OrderBy operator will sort values in ascending order. ThenBy is used after OrderBy to sort the collection data on another field in ascending order. LINQ will first sort the collection based on primary field which is specified by OrderBy and then resulted collection is sorted into ascending order again based on secondary field specified by ThenBy.

ThenByDescending

Just like ThenBy, ThenByDescending is used to sort data in descending order.

Reverse

Reverse operator simply sort collection data in reverse order.

Using ThenBy And ThenByDescending Method

To understand this, I have created a Employee class with 3 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 static List<Employee> GetAllEmployees()
  {
    Employee emp1 = new Employee { Id = 1, Name = "Yogesh", DeptId = 102 };
    Employee emp2 = new Employee { Id = 4, Name = "Rahul", DeptId = 101 };
    Employee emp3 = new Employee { Id = 3, Name = "Anil", DeptId = 102 };
    Employee emp4 = new Employee { Id = 2, Name = "Anil", DeptId = 101 };
    Employee emp5 = new Employee { Id = 5, Name = "Rahul", DeptId = 101 };

    List<Employee> empList = new List<Employee>();

    empList.Add(emp1);
    empList.Add(emp2);
    empList.Add(emp3);
    empList.Add(emp4);
    empList.Add(emp5);

    return empList;
  }
}

Now, let's print all employee's details before applying any kind of sorting.

static void Main(string[] args)
{
  List<Employee> obj = Employee.GetAllEmployees();

  Console.WriteLine("Before Sorting:");
  foreach (Employee e in obj)
  {
      Console.WriteLine(e.DeptId+"\t"+e.Name+"\t"+e.Id);
  }
  Console.ReadKey();
}

class Employee
{
  public int Id;
  public string Name;
  public int DeptId;

  public static List<Employee> GetAllEmployees()
  {
    Employee emp1 = new Employee { Id = 1, Name = "Yogesh", DeptId = 102 };
    Employee emp2 = new Employee { Id = 4, Name = "Rahul", DeptId = 101 };
    Employee emp3 = new Employee { Id = 3, Name = "Anil", DeptId = 102 };
    Employee emp4 = new Employee { Id = 2, Name = "Anil", DeptId = 101 };
    Employee emp5 = new Employee { Id = 5, Name = "Rahul", DeptId = 101 };

    List<Employee> empList = new List<Employee>();

    empList.Add(emp1);
    empList.Add(emp2);
    empList.Add(emp3);
    empList.Add(emp4);
    empList.Add(emp5);

    return empList;
  }
}

Output can be seen as below. First column is DeptId, 2nd is Name and 3rd is Id.

Before Sorting

Now, we will apply OrderBy on DeptId field to sort DeptId in ascending order and ThenBy on Name field to sort Name in ascending order.

static void Main(string[] args)
{
  IEnumerable<Employee> sortedResult = Employee.GetAllEmployees().OrderBy(x => x.DeptId).ThenBy(x => x.Name);

  Console.WriteLine("After Sorting DeptId and Name:");
  foreach (Employee e in sortedResult)
  {
      Console.WriteLine(e.DeptId + "\t" + e.Name + "\t" + e.Id);
  }
  Console.ReadKey();
}

As you can DeptId is sorted in ascending order and Name is also sorted in ascending.

After OrderBy and ThenBy

Now, we will apply OrderBy on DeptId field to sort DeptId in ascending order, ThenBy on Name field to sort Name in ascending order and ThenByDescending on Id field to sort Id in descending order.

static void Main(string[] args)
{
  IEnumerable<Employee> sortedResult = 
  Employee.GetAllEmployees().OrderBy(x => x.DeptId).ThenBy(x => x.Name).ThenByDescending(x => x.Id);

  Console.WriteLine("After Sorting All Columns:");
  foreach (Employee e in sortedResult)
  {
      Console.WriteLine(e.DeptId + "\t" + e.Name + "\t" + e.Id);
  }
  Console.ReadKey();
}

As you can se Id is sorted in descending order. 2nd and 3rd row got interchanged.

After OrderBy, ThenBy and ThenByDescending

Using ThenBy And ThenByDescending AS SQL Like Syntax

Now, same thing can be achieved using orderby in sql syntax. Here orderby keyword will sort DeptId field and Name field in ascending order by-default and Id field will be sorted in descending order using descending keyword.

static void Main(string[] args)
{
  IEnumerable<Employee> sortedResult = from e in Employee.GetAllEmployees()
                                                          orderby e.DeptId, e.Name, e.Id descending
                                                          select e;

  foreach (Employee e in sortedResult)
  {
      Console.WriteLine(e.DeptId + "\t" + e.Name + "\t" + e.Id);
  }
  Console.ReadKey();
}

Using Reverse Method

Now, we will use Reverse method to sort collection data in reverse order.

static void Main(string[] args)
{
  IEnumerable<Employee> ObjEmp = Employee.GetAllEmployees();
                                      
  Console.WriteLine("Before Reverse");
  foreach (Employee e in ObjEmp)
  {
      Console.WriteLine(e.DeptId + "\t" + e.Name + "\t" + e.Id);
  }

  Console.WriteLine();

  IEnumerable<Employee> ObjEmpReverse= ObjEmp.Reverse();

  Console.WriteLine("After Reverse");
  foreach (Employee e in ObjEmpReverse)
  {
      Console.WriteLine(e.DeptId + "\t" + e.Name + "\t" + e.Id);
  }

  Console.ReadKey();
}
Before and after Reverse

LINQ Ordering (Sorting) Operators: OrderBy and OrderByDescending in C#

LINQ Ordering (Sorting) Operators: OrderBy and OrderByDescending in C#

In this article, we are going to learn LINQ ordering (sorting) operators in C# with examples. LINQ sorting operators are used to arrange the collection data into ascending or descending order based on one or more attributes (fields). Below are the five sorting operator.
1. OrderBy
2. OrderByDescending
3. ThenBy
4. ThenByDescending
5. Reverse

In this tutorial, we are going to learn OrderBy and OrderByDescending operators only. Click here to read ThenBy, ThenByDescending and Reverse Operators.

OrderBy

OrderBy operator will sort values in ascending order. It sorts collection data in ascending order by default, here ascending keyword is optional.

OrderByDescending

OrderByDescending operator will sort values in descending order.

ThenBy

OrderBy operator will sort values in ascending order. ThenBy is used after OrderBy to sort the collection data on another field in ascending order. LINQ will first sort the collection based on primary field which is specified by OrderBy and then resulted collection is sorted into ascending order again based on secondary field specified by ThenBy.

ThenByDescending

Just like ThenBy, ThenByDescending is used to sort data in descending order.

Reverse

Reverse operator simply sort collection data in reverse order.

Related Articles

  1. Introduction to LINQ Standard Query Operators Vs SQL

Using OrderBy Method

To understand this, I have created a Employee class with 3 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 static List<Employee> GetAllEmployees()
    {
        Employee emp1 = new Employee { Id = 1, Name = "Rahul", DeptId = 102 };
        Employee emp2 = new Employee { Id = 4, Name = "Anil", DeptId = 101 };
        Employee emp3 = new Employee { Id = 3, Name = "Yogesh", DeptId = 102 };
        Employee emp4 = new Employee { Id = 2, Name = "Mary", DeptId = 101 };

        List<Employee> empList = new List<Employee>();

        empList.Add(emp1);
        empList.Add(emp2);
        empList.Add(emp3);
        empList.Add(emp4);

        return empList;
    }
}

Let us print all employee's name before applying sorting.

class Program
{
    static void Main(string[] args)
    {
        List<Employee> obj = Employee.GetAllEmployees();

        Console.WriteLine("Before Sorting:");
        foreach (Employee e in obj)
        {
            Console.WriteLine(e.Name);
        }
    }
}
class Employee
{
    public int Id;
    public string Name;
    public int DeptId;

    public static List<Employee> GetAllEmployees()
    {
        Employee emp1 = new Employee { Id = 1, Name = "Rahul", DeptId = 102 };
        Employee emp2 = new Employee { Id = 4, Name = "Anil", DeptId = 101 };
        Employee emp3 = new Employee { Id = 3, Name = "Yogesh", DeptId = 102 };
        Employee emp4 = new Employee { Id = 2, Name = "Mary", DeptId = 101 };

        List<Employee> empList = new List<Employee>();

        empList.Add(emp1);
        empList.Add(emp2);
        empList.Add(emp3);
        empList.Add(emp4);

        return empList;
    }
}
/*
OUTPUT
Before Sorting:
Rahul
Anil
Yogesh
Mary
*/

Now will be applying sorting using OrderBy on Name property.

static void Main(string[] args)
{
    List<Employee> obj = Employee.GetAllEmployees();

    Console.WriteLine("Before Sorting:");
    foreach (Employee e in obj)
    {
        Console.WriteLine(e.Name);
    }

    Console.WriteLine();

    IEnumerable<Employee> sortedResult = Employee.GetAllEmployees().OrderBy(x => x.Name);

    Console.WriteLine("After Sorting:");
    foreach (Employee e in sortedResult)
    {
        Console.WriteLine(e.Name);
    }
    Console.ReadKey();
}
/*
OUTPUT
Before Sorting:
Rahul
Anil
Yogesh
Mary

After Sorting:
Anil
Mary
Rahul
Yogesh
*/

Using orderby As SQL Like Syntax

Now will use SQL like syntax.

static void Main(string[] args)
{
  IEnumerable<Employee> sortedResult = from emp in Employee.GetAllEmployees()
                                       orderby emp.Name // by default ascending order
                                       select emp;
  
  Console.WriteLine("After Sorting:");
  foreach (Employee e in sortedResult)
  {
      Console.WriteLine(e.Name);
  }
  Console.ReadKey();
}  
/*
OUTPUT
After Sorting:
Anil
Mary
Rahul
Yogesh
*/

Using OrderByDescending Method

Now will be applying sorting using OrderByDescending on Name property.

static void Main(string[] args)
{
  IEnumerable<Employee> sortedResult = Employee.GetAllEmployees().OrderByDescending(x => x.Name);

  Console.WriteLine("After Sorting:");
  foreach (Employee e in sortedResult)
  {
      Console.WriteLine(e.Name);
  }
  Console.ReadKey();
}  
/*
OUTPUT
After Sorting:
Yogesh
Rahul
Mary
Anil
*/

Using orderby with descending As SQL Like Syntax

Now will use SQL like syntax to sort them in descending order.

static void Main(string[] args)
{
  IEnumerable<Employee> sortedResult = from emp in Employee.GetAllEmployees()
                                       orderby emp.Name  descending
                                       select emp;

  Console.WriteLine("After Sorting:");
  foreach (Employee e in sortedResult)
  {
      Console.WriteLine(e.Name);
  }
  Console.ReadKey();
}  
/*
OUTPUT
After Sorting:
Yogesh
Rahul
Mary
Anil
*/

Sorting C# Array using OrderBy and OrderByDescending

string[] Subjects = { "Joomla", "C++", "VB", "Java", "ASP.Net", "C", "Perl" };

var sortedSubjects1 = from s in Subjects
                     orderby s
                     select s;
Console.WriteLine("After sorting in ascending order using sql like query");
foreach (string s in sortedSubjects1)
{
    Console.WriteLine(s);
}
/*
OUTPUT:
ASP.Net
C
C++
Java
Joomla
Perl
VB 
*/

var sortedSubjects2 = from s in Subjects
                     orderby s descending
                     select s;
Console.WriteLine("After sorting in descending order using sql like query");
foreach (string s in sortedSubjects2)
{
    Console.WriteLine(s);
}
/*
OUTPUT:
VB
Perl
Joomla
Java
C++
C
ASP.Net
*/

var sortedSubjects3 = Subjects.OrderBy(x => x);
Console.WriteLine("After sorting in ascending order using OrderBy method");
foreach (string s in sortedSubjects3)
{
    Console.WriteLine(s);
}
/*
OUTPUT:
ASP.Net
C
C++
Java
Joomla
Perl
VB 
*/

var sortedSubjects4 = Subjects.OrderByDescending(x => x);
Console.WriteLine("After sorting in descending order using OrderByDescending method");
foreach (string s in sortedSubjects4)
{
    Console.WriteLine(s);
}
Console.ReadKey();
/*
OUTPUT:
VB
Perl
Joomla
Java
C++
C
ASP.Net
*/

Sorting C# Array using OrderBy and OrderByDescending with Length Property

string[] Subjects = { "Joomla", "C++", "VB", "Java", "ASP.Net", "C", "Perl" };

var sortedSubjects1 = from s in Subjects
                      orderby s.Length  //you can use descending keyword after s.Length
                      select s;

Console.WriteLine("After Sorting");
foreach (string s in sortedSubjects1)
{
    Console.WriteLine(s);
}
/*
OUTPUT:
C
VB
C++
Java
Perl
Joomla
ASP.Net
*/

Console.WriteLine();

var sortedSubjects2 = Subjects.OrderByDescending(x => x.Length);

Console.WriteLine("After Sorting");
foreach (string s in sortedSubjects2)
{
    Console.WriteLine(s);
}
Console.ReadKey();
/*
OUTPUT:
ASP.Net
Joomla
Perl
Java
C++
VB
C
*/

LINQ Restriction and Projection Operators in C# with example

LINQ Restriction and Projection Operators in C# with example

In this article, we are going to learn LINQ restriction and projection operators in details with the examples. The Where standard query operator belong to restriction operators category. Where query operator is same as that of Where clause in SQL. Where query operator is used to filter the rows. The filter expression is specified using predicate. It restricts the sequence returned by a query based on a predicate provided as an argument. A predicate is a function to test each element for a condition. One important thing is that Where query operator is optional.

Related Articles

  1. Introduction to LINQ Standard Query Operators Vs SQL

LINQ Where operator

Example 1

Let us understand restriction operator with an example.
In this example, we have taken integer List of 10 numbers. We want to find those numbers that are greater than 5. We will be writing LINQ query using lambda expression.

static void Main(string[] args)
{
  List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  
  IEnumerable<int> GreaterNum = numbers.Where(x => x > 5);
  
  foreach (int item in GreaterNum)
  {
      Console.WriteLine(item);
  }
  Console.ReadKey();
}
/*
OUTPUT:
6
7
8
9
10
*/

Here the x => x > 5 is the predicate expression that are going to operate on each item of numbers collection. "x" is the source (integer) and "x > 5" is the boolean expression. Below is the 2 overloaded versions of Where extension method in Enumerable class.

public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
/*
 Summary:
     Filters a sequence of values based on a predicate.

 Parameters:
   source:
     An System.Collections.Generic.IEnumerable<T> to filter.

   predicate:
     A function to test each element for a condition.

 Type parameters:
   TSource:
     The type of the elements of source.

 Returns:
     An System.Collections.Generic.IEnumerable<T> that contains elements from
     the input sequence that satisfy the condition.

 Exceptions:
   System.ArgumentNullException:
     source or predicate is null.
*/
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
/*
 Summary:
     Filters a sequence of values based on a predicate. Each element's index is
     used in the logic of the predicate function.
 
 Parameters:
   source:
     An System.Collections.Generic.IEnumerable<T> to filter.
 
   predicate:
     A function to test each source element for a condition; the second parameter
     of the function represents the index of the source element.
 
 Type parameters:
   TSource:
     The type of the elements of source.
 
 Returns:
     An System.Collections.Generic.IEnumerable<T> that contains elements from
     the input sequence that satisfy the condition.
 
 Exceptions:
   System.ArgumentNullException:
     source or predicate is null.
*/

Example 2

Here in above example, we can create explicit Func and pass it to Where method as shown below.

static void Main(string[] args)
{
  List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  
  // x is integer (source)
  // x > 5 is boolean condition
  
  Func<int, bool> predicate = x => x > 5;

  IEnumerable<int> GreaterNum = numbers.Where(predicate);

  foreach (int item in GreaterNum)
  {
      Console.WriteLine(item);
  }
  Console.ReadKey();
}
/*
OUTPUT:
6
7
8
9
10
*/

Example 3

We can create a explicit function and can pass it to the Where extension method as shown below.

static void Main(string[] args)
{
  List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

  IEnumerable<int> GreaterNum = numbers.Where(x => (funGraterNum(x)));

  foreach (int item in GreaterNum)
  {
      Console.WriteLine(item);
  }
  Console.ReadKey();
}
public static bool funGraterNum(int number)
{
  if (number > 5)
  {
      return true;
  }
  else
  {
      return false;
  }
  
  // we can use 
  //return number > 5;
}
/*
OUTPUT:
6
7
8
9
10
*/

LINQ Select Operator

Example 1

Now, we can achieve the same thing using LINQ select operator.

static void Main(string[] args)
{
 List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

 IEnumerable<int> GreaterNum = from num in numbers
                               where num > 5
                               select num;

 foreach (int item in GreaterNum)
 {
     Console.WriteLine(item);
 }
 Console.ReadKey();
}

LINQ with Where - Indexed

Example 1

Now, we will use the 2nd overloaded versions of Where extension method to find out the index of each item.

static void Main(string[] args)
{
  List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  
  var GreaterNum = numbers.Select((num, index) => new {Number=num, Index=index });
  
  foreach (var item in GreaterNum)
  {
      Console.WriteLine("Number: " + item.Number+ " Index:" + item.Index);
  }
  Console.ReadKey();
}
/*
OUTPUT:
Number: 1  Index 0
Number: 2  Index 1
Number: 3  Index 2
Number: 4  Index 3
Number: 5  Index 4
Number: 6  Index 5
Number: 7  Index 6
Number: 8  Index 7
Number: 9  Index 8
Number: 10 Index 9
*/

Example 2

Now, find those number that are greater than 5 along with index.

static void Main(string[] args)
{
  List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

  var GreaterNum = numbers.Select((num, index) => new { Number = num, Index = index })
                  .Where(x => x.Number > 5);

  foreach (var item in GreaterNum)
  {
      Console.WriteLine("Number: " + item.Number + " Index:" + item.Index);
  }
  Console.ReadKey();
}
/*
OUTPUT:
Number: 6  Index 5
Number: 7  Index 6
Number: 8  Index 7
Number: 9  Index 8
Number: 10 Index 9
*/

Example 3

Now, find index for those number that are greater than 5.

static void Main(string[] args)
{
  List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  
  var GreaterNum = numbers.Select((num, index) => new { Number = num, Index = index })
                  .Where(x => x.Number > 5)
                  .Select(x => x.Index);
  
  foreach (var item in GreaterNum)
  {
      Console.WriteLine("Index:" + item);
  }
  Console.ReadKey();
}
/*
OUTPUT:
Index 5
Index 6
Index 7
Index 8
Index 9
*/

LINQ with Where - StartsWith function

Example 1

Now, find item whose name start with C.

static void Main(string[] args)
{
  List<string> language = new List<string> { "Java","C",".Net","C#","HTML","SQL","C++" };
  
  IEnumerable<string> result = language.Where(x => x.StartsWith("C"));
  
  foreach (string item in result)
  {
      Console.WriteLine("Item name starts with C: " + item);
  }
  Console.ReadKey();
}
/*
OUTPUT:
Item name starts with C: C
Item name starts with C: C#
Item name starts with C: C++
*/

LINQ with Where - StartsWith, ToUpper, Index function

Example 2

Now, find those items whose name start with C and convert into upper case and find length and index.

static void Main(string[] args)
{
  List<string> language = new List<string> { "Java", "c", ".Net", "C#", "HTML", "SQL", "c++" };
  
  var result = language.Select((x, i) => new {
      Subject = x,
      Upper = x.ToUpper(),
      Length = x.Length,
      Index = i,
  })
  .Where(x => x.Subject.StartsWith("C", StringComparison.CurrentCultureIgnoreCase));
  
  foreach (var item in result)
  {
      Console.WriteLine("Subject: " + item.Subject + " ToUpper: " + item.Upper 
                       + " Length: " + item.Length + " Index: " + item.Index);
  }
  Console.ReadKey();
}
/*
OUTPUT:
Subject: C    ToUpper: C   Length: 1 Index: 1
Subject: C#   ToUpper: C#  Length: 2 Index: 3
Subject: C++  ToUpper: C++ Length: 3 Index: 6
*/