Skip Navigation LinksHome > Categories > Code from a Category

Simple LINQ Queries



User Name: codelecturer
Name: Mike Chauhan
Contact Me: www.datawebcoder.com/ContactUs.aspx
Home Page: www.datawebcoder.com
6 years of total IT experience including programming, application development, System Maintenance . 3 years of Experienced and expertise in .Net Framework VB, Visual Basic.Net, ASP.Net 2.0, 3.5 and AD... [More]
Viewed Times: 1047
Add Date: 12/08/2012
In this article we will learn some Simple LINQ Queries

Querying

The article will then explain how the same, or similar, queries can be created using the query expression syntax.

In this article we will use the Where operator. This is also known as the restriction operator. It allows a collection of items to be filtered according to a Boolean condition, or predicate.

The result of the operation is a collection containing all of the items that, when the predicate is applied, return a true result. Those that do not meet the condition are excluded from the results.

Where Operator

The Where operator is a standard query operator. As such, it is an extension method for collections that implement the generic IEnumerable interface. When used as an extension method, one parameter is supplied. This is a Func delegate that accepts the predicate. Although any delegate with an appropriate signature can be supplied to the parameter, it is commonplace to use a lambda expression that returns a Boolean value. The lambda expression may then be applied to every item in the source data to determine which items should be included in the results and which should be omitted.

As with many standard query operators, the execution of the Where method is deferred, being executed "just-in-time". Usually this means that the predicate is evaluated for each item and the resultant collection is returned when it is first accessed. Until then, the result of the Where clause is an IEnumerable that stores the information required to run the query but not the actual results.

The following code demonstrates the Where operator by executing a simple string query. First, an array of strings containing the colours of the rainbow is instantiated and initialised. This can be queried directly because all arrays implement IEnumerable, with T being the array's type. The second line defines the query with a lambda expression specifying that only colours with five or more characters in the name will be included in the results. The results are then outputted to the console.


The type to use in the lambda expression is inferred from its usage, hence the Length property being available in the previous example. This means that you can query a collection of any type and access all of the methods, properties and public fields provided by the class or structure. We can demonstrate further with an example that queries a collection that holds objects of a custom class. First, we need to create the type. The following code creates an Employee class that holds the name, title and salary of a single employee in three properties. The class includes a constructor that allows each of these properties to be set. It also overrides the ToString method to simplify output of query results.


With the class created we can provide some sample data in a collection. In this example we will use a generic list instead of an array. The list holds data for four employees.

As a simple example, we may wish to obtain a list of employees that are developers. These are those with the word "Developer" in their job title. This is easy to achieve using the Title property and the Contains method, which is a member of the string class. The following query should return Bob, Sam and Mel in the results. Jim is excluded.

For more complex queries you can add to the predicate using the C# Boolean operators. The next example uses a combination of the AND and OR operators. It returns all developers with a salary greater than £35,000 and all non-developers with a salary lower than £25,000. The results include Bob and Jim only.

Restrictions and Query Expression Syntax

In this section we will recreate the queries from above using the Query Expression syntax. This is the more natural syntax that some developers prefer to use to generate queries. The two syntaxes are equally valid and both should be considered for their suitability according to the task being undertaken. For example, you may decide to use the extension methods when working with other C# developers and to use the query syntax when working closely with SQL users.

The basic form of the query expression syntax is as follows:

In this syntax, the results element receives the results of the query. As with the standard query operators, the result is usually an IEnumerable object that contains all of the information required to generate the query's results. The results are usually generated using deferred execution when they are needed. Here I have declared the type for the results implicitly using the var keyword.

The from clause includes two important elements. The data source specifies the data structure that contains the items to be queried. The range variable is a variable that becomes available to the rest of the query to represent each item. In this article we will see how it is used to specify the predicate that filters the results. In future articles we will see how it can be used to determine the structure of the returned data and to control other operations, such as sorting.

The where clause provides the restrictions to apply when filtering the data source. The predicate is a Boolean expression that is very similar to the lambda expression used in earlier examples. The syntax differs slightly as no lambda operator or parameters are supplied.

The final section in this simple syntax is the select clause. The projection element determines which elements of the data source are returned. In this article we will return the entire object for each valid result. In the next article we will see how other projections are possible.

To demonstrate the syntax, we can recreate the earlier examples. The first example queried an array of strings containing the names of colours. Only colours with a string length of five or greater were included in the results. This can be expressed as a query as follows:

In the above code, the results are returned in the longNames variable. The range variable is named "c". It is common to see short or single-character range variable names, though longer names are acceptable and can improve code clarity. The where clause specifies that the length of c must be greater than or equal to five for an item from the data source, colours, to be included in the results. The select clause specifies that for each result, the "c" object will be returned.

Let's recreate the second sample, which retrieved all employees from a list if their job title included the word, "Developer":

Again, the syntax is reasonably simple. You can almost read the query as plain English: For each employee, if the Title property contains the string, "Developer", add it to the results. To complete the conversions, we can express the more complex employee query using the query syntax. In this case Boolean operators were used to combine the predicate's conditions:

Simplifying Queries with the Let Clause

The query expression syntax can become long-winded, especially when using complex queries. Even in the previous sample, there is duplication because employees' titles are checked twice to see if they include the word, "Developer". Luckily, LINQ queries include a clause that can simplify such queries. The let clause allows you to define additional range variables that are calculated once for each item in the data source. We can improve the efficiency of our query by introducing a range variable that pre-calculates a Boolean value that specifies whether the employee is a developer:

The let clause in the above query reduces the complexity of the query and lowers the number of calculations that are performed. In very complex queries this can be extremely useful. Querying IEnumerable Collections

So far we have executed queries against generic collections, which specify and enforce the type of each item in the data source. This makes type inference possible for lambda expressions and range variables. Sometimes you will need to query collections or data structures that implement the IEnumerable interface but not its generic counterpart. In these cases it is not possible to guarantee the type of each item and type inference fails. When using standard query operators, you can resolve the problem by using the Cast method. This is an extension method to the IEnumerable interface that allows you to specify the type of the data items and obtain an IEnumerable. The Where method can then use the results of Cast, knowing the type that is to be queried. The Cast method uses deferred execution so is applied only when its results are used. This means that the Cast and Where operators may be applied as a single operation. The query will fail if any element in the data source cannot be converted to the specified type.

The following shows the Case and Where methods used together to query an ArrayList.

Specifying the type when using query expression syntax is equally simple. Instead of using a Cast operator, the type to assume for each data source item is provided with the range variable. Note the use of the "string" data type before the "c" range variable in the following example. Without this the code would not compile.


Happy Programming!!!

Post a Comment

Name: (Optional)
Email: (Optional, you can get an email if somebody replys your comments)*
Email me if somebody respons my comment below:
Details**:
Enter Text
as Below:
(case insensitive, if hard to read, click the "get a new one" button)
 
    
* Your email address will not be shared with any third parties for any reason.
** Maximum 1000 charactors.