Thursday, 9 February 2017

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
*/
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON