Restriction and Projection Operators in LINQ


Want to learn about the LINQ Operators? This article would discuss about restriction and projection LINQ operators and how to use these LINQ operators in your program.

In this article we will learn how to use LINQ operators in our application. I would also be covering the entire range of Linq functionality in this sample code.

Before we proceed to the coding for using LINQ operators I would like to first briefly describe what is LINQ.

Defination of LINQ as given in books: Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# which have many operators. We will look through the restriction and Partition operators of LINQ.

Restriction Operator of LINQ



1. Where Clause

Suppose we have a list of strings and we want to filter it by the names which starts with 'A'.
string[] names = { "Asyl", "Bail", "Manu", "Agni", "Jay" };


In fluent syntax the query will be...
IEnumerable query = names.Where (name => name.StartsWith ("A"));
foreach(var item in query)
{
Console.WriteLine(item);
}
//Output
Asyl
Agni


In normal query syntax...
IEnumerable query = from n in names
where n.StartsWith ("y")
select n;
foreach(var item in query)
{
Console.WriteLine(item);
}
//Output
Asyl
Agni


Projection Operators of LINQ



1. Select Clause

Suppose we have a list of numbers and we want to select the numbers by adding 1 to it.
var numbers = { 6, 9, 4, 3, 0, 1 };
var query = from n in numbers select n+1;
foreach(var item in query)
{
Console.WriteLine(item);
}
//OutPut
7
10
5
4
1
2


2. Select Many Clause
Suppose we have two lists of numbers and we want to select the numbers from both the list where listA is less than listB.
var listA = { 6, 9, 4, 3, 0, 1 };
var listB = { 1, 2, 5, 8, 9, 5, 4};

var query = from a in listA
from b in listB
where a < b
select new {a,b};
foreach(var item in query)
{
Console.WriteLine(item.a + " < " + item.b);
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: