C# LINQ into Query Keyword

Updated on 13 Sep 2012,
Published on 13 Sep 2010

The into keyword of LINQ query expressions is a contextual keyword that allows you to create a new temporary identifier for storing the results sequence retrieved from group, join or select clause into a new identifier. The use of new identifier is also referred to as continuation that enables you to continue the query expression by applying additional query operation on each group. The most common example of using into keyword in LINQ query is applying the where clause predicate condition on the new identifier.

Syntax for LINQ into keyword

from <range-variable> in <data source sequence object>
group <range-variable> by <group-key criteria> into <new identifier>

The above syntax shows that the group results sequence can be stored in a new identifier specified after the into keyword in the group statement of LINQ query expression. If you will use the select clause as a next expression e.g. select <new identifier> then it will return the result as a sequence of IGrouping<TKey, TElement> object. Otherwise you can also project the output with new anonymous type.

Example for LINQ into keyword using C# in ASP.Net

string[] fruits = { "oranges", "grapes", "guava", "plums", "raspberries", "gooseberries", "pineapples" };

var query = from fruit in fruits
            group fruit by fruit[0] into fGroup
            where fGroup.Count() > 1
            select fGroup;

foreach (var fruitsGroup in query)
{
    Response.Output.Write("Group \"{0}\" contains \"{1}\" fruits:<br />", fruitsGroup.Key, fruitsGroup.Count());

    foreach (string fruitName in fruitsGroup)
    {
        Response.Output.Write("{0}<br />", fruitName);
    }
}

// Output:
// Group "g" contains "3" fruits:
// grapes
// guava
// gooseberries
// Group "p" contains "2" fruits:
// plums
// pineapples

In the above C# LINQ example for into keyword we have stored the group sequence result into the fGroup identifier. In the next expression we have applied the where clause predicate to check the count of items available for each group. The above LINQ query expression will return the groups containing items more than 1 only.

Continue to the next tutorial: LINQ orderby Clause using C# in ASP.Net to learn how to sort the result sequence retrieved after the execution of a query expression.

0 Responses to "C# LINQ into Query Keyword"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers