How to LINQ? Part-2: Query Expressions

Query Expressions

 

The main learning curve for an application developer who is new to LINQ is the query syntax. This declarative syntax requires minimum code by which you can even perform fairly complex queries. Let us look at some code snippets for example:

 

A simple select query – Selecting the marks from the array which are above 50

 

int[] marks  = { 85, 40, 75, 60 };

 

var passedMarks =
from m in marks

where m>50
select m;

 

Console.WriteLine(“Selected Marks :”);
    foreach (var i in passedMarks) {
        Console.WriteLine(i);
    }

 

Output:

 

Selected Marks :

85

75

60

 

 

 

MSDN tells about the three distinct parts of a LINQ query

 

  1. Obtain the data source.
  2. Create the query.
  3. Execute the query

 

Let us relate this to the first example:

 

Obtain the data source

int[] marks  = { 85, 40, 75, 60 };

 

Create the query

var passedMarks =
from m in marks

where m>50
select m;

 

Execute the query

Console.WriteLine(“Selected Marks :”);
    foreach (var i in passedMarks) {
        Console.WriteLine(i);
    }

 

Advertisements

2 thoughts on “How to LINQ? Part-2: Query Expressions

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s