how does a linq query work
How does a LINQ query work and what are its basic operations. A LINQ query identifies the data source, builds the query and executes the query and can be looked at as consisting of three sections.
In the first section, the data source is identified.
In the second section, the linw query is built.
The from clause specifies LINQ to query the customers collection and the name cust is used to specify how to treat each element of data in the collection. In the above query, cust is called range variable.
The where clause specifies the data from the collection to be included. If your query includes an order by clause LINQ sorts the results in ascending order by default. Observe that the query is of type IEnumerable
. This can be verified by checking whether the results are of enumeration of type string. Now, building the query is completed.
In the third section, the linq query is executed.
We iterate through the query result and display the final result. Iteration is usually done through foreach loop. When the iteration commences we can say that the execution of the query has started.
The below code demonstrates how to build and execute LINQ query to retrieve all the continents in a collection.
The section1 creates and add the data to the data source.
The section2 builds the query
The section3 executes the query
//Section1
List continents = new List();
continents.Add("Asia");
continents.Add("Africa");
continents.Add("NorthAmerica");
continents.Add("Australia");
//Section2
IEnumerable query = from c in continents
where c.Length > 5
orderby c
select c;
//Section3
foreach (string continent in query)
{
Console.WriteLine(continent);
}
example of using LINQ query to retrieve data from a string array.
class LINQExample
{
static void Main()
{
//section1:
string[] names = new string[4] { �John�, �Jo�, �Jack�, �Jill� };
// Section2:
var query = from n in names
where n == �Jo�
select n;
// section3:
foreach (int name in query)
{
Console.Write("{0,1} ", name);
}
}
}
To enable LINQ in the VS 2008 project, we need to add a reference to the System.Core.dll and place the statement: using System.Linq;