Blog from Saravanan Arumugam

Let us talk about Technologies

Chaining the result in Linq


In linq, extension method is a nice way to chain the result of one query to another and so on.

For example

var fileData = File.ReadAllLines(this.FileName)
                        .Select(line => line.Split('.'))
                        .Select(columns => new
                        {
                            Column1 = columns[0],
                            Column2 = columns[1],
                            Column3 = columns[2],
                            Column4 = columns[3]
                        }
                        );

In the example above, the result of first select goes as the input to the next select and this operation can go seamlessly to any level.

For writing the same query in the sugared linq syntax (with from … select syntax), you can take two approaches.

1. Use let keyword

let keyword can introduce a new variable in addition to the iteration variable and can appear in the middle of the query.

var fileData = (from line in File.ReadAllLines(file)
             let columns = line.Split(',')
             select new
             {
                 Column1 = columns[0],
                 Column2 = columns[1],
                 Column3 = columns[2],
                 Column4 = columns[3]
             }).ToList();

2. Use into keyword

into keyword is an ideal replacement of extension method based example shown above. into brings the result of a query operation to an intermediate queryable result set, which can further be queried.

var fileData1 = (from line in File.ReadAllLines(file)
                 select line.Split(',')
                     into columns
                     select new
                     {
                         Column1 = columns[0],
                         Column2 = columns[1],
                         Column3 = columns[2],
                         Column4 = columns[3]
                     }
                         // just to show that this can be 
                         // exetended to any level
                         into someNewResultSet 
                         select someNewResultSet
                     ).ToList();
Advertisements

One response to “Chaining the result in Linq

  1. Arun March 8, 2012 at 2:53 am

    Good one dude 🙂

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

%d bloggers like this: