Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

C# LINQ Keywords - The orderby Clause

The orderby clause is used to sort the sequence of results in a query. Following the orderby keyword is the item you want to sort by, which is commonly some property of the range variable. You can sort in either ascending or descending order, and if you don’t specify that with either the ascending or descending keyword, ascending is the default order. Following the orderby clause, you can have an unlimited set of subsorts simply by separating each sort item with a comma, as demonstrated here:

using System;
using System.Linq;
using System.Collections.Generic;

public class Employee
{
public string LastName { get; set; }
public string FirstName { get; set; }
public string Nationality { get; set; }
}

public class OrderByExample
{
static void Main() {
var employees = new List() {
new Employee {
LastName = "Glasser", FirstName = "Ed",
Nationality = "American"
},
new Employee {
LastName = "Pupkin", FirstName = "Vasya",
Nationality = "Russian"
},
new Employee {
LastName = "Smails", FirstName = "Spaulding",
Nationality = "Irish"
},
new Employee {
LastName = "Ivanov", FirstName = "Ivan",
Nationality = "Russian"
}
};

var query = from emp in employees
orderby emp.Nationality,
emp.LastName descending,
emp.FirstName descending
select emp;
foreach( var item in query ) {
Console.WriteLine( "{0},\t{1},\t{2}",
item.LastName,
item.FirstName,
item.Nationality );
}
}
}

Notice that because the select clause simply returns the range variable, this whole query expression is nothing more than a sort operation. But it sure is a convenient way to sort things in C#. In this example, I sort first by Nationality in ascending order, then the second expression in the orderby clause sorts the results of each nationality group by LastName in descending order, and then each of those groups is sorted by FirstName in descending order.

At compile time, the compiler translates the first expression in the orderby clause into a call to the OrderBy standard query operator extension method. Any subsequent secondary sort expressions are translated into chained ThenBy extension method calls. If orderby is used with the descending keyword, the generated code uses OrderByDescending and ThenByDescending respectively.

Source Of Information : Apress Accelerated C Sharp 2010

C# LINQ Keywords - The where Clause and Filters

Following one or more from clause generators or the join clauses if there are any, you typically place one or more filter clauses. Filters consist of the where keyword followed by a predicate expression. The where clause is translated into a call to the Where extension method, and the predicate is passed to the Where method as a lambda expression. Calls to Enumerable.Where, which are used if you are performing a query on an IEnumerable type, convert the lambda expression into a delegate. Conversely, calls to Queryable.Where, which are used if you perform a query on a collection via an IQueryable interface, convert the lambda expression into an expression tree.

Source Of Information : Apress Accelerated C Sharp 2010

C# LINQ Keywords - The join Clause

Following the from clause, you might have a join clause used to correlate data from two separate sources. Join operations are not typically needed in environments where objects are linked via hierarchies and other associative relationships. However, in the relational database world, there typically are no hard links between items in two separate collections, or tables, other than the equality between items within each record. That equality operation is defined by you when you create a join clause. Consider the following example:
<pre class="brush:csharp">
using System;
using System.Linq;
using System.Collections.Generic;

public class EmployeeId
{
public string Id { get; set; }
public string Name { get; set; }
}

public class EmployeeNationality
{
public string Id { get; set; }
public string Nationality { get; set; }
}

public class JoinExample
{
static void Main() {
// Build employee collection
var employees = new List<EmployeeId>() {
new EmployeeId{ Id = "111-11-1111",
Name = "Ed Glasser" },
new EmployeeId{ Id = "222-22-2222",
Name = "Spaulding Smails" },
new EmployeeId{ Id = "333-33-3333",
Name = "Ivan Ivanov" },
new EmployeeId{ Id = "444-44-4444",
Name = "Vasya Pupkin" }
};

// Build nationality collection.
var empNationalities = new List<EmployeeNationality>() {
new EmployeeNationality{ Id = "111-11-1111",
Nationality = "American" },
new EmployeeNationality{ Id = "333-33-3333",
Nationality = "Russian" },
new EmployeeNationality{ Id = "222-22-2222",
Nationality = "Irish" },
new EmployeeNationality{ Id = "444-44-4444",
Nationality = "Russian" }
};

// Build query.
var query = from emp in employees
join n in empNationalities
on emp.Id equals n.Id
orderby n.Nationality descending
select new {
Id = emp.Id,
Name = emp.Name,
Nationality = n.Nationality
};

foreach( var person in query ) {
Console.WriteLine( "{0}, {1}, \t{2}",
person.Id,
person.Name,
person.Nationality );
}
}
}
</pre>
In this example, I have two collections. The first one contains just a collection of employees and their employee identification numbers. The second contains a collection of employee nationalities in which each employee is identified only by employee ID. To keep the example simple, every piece of data is a string. Now, I want a list of all employee names and their nationalities and I want to sort the list by their nationality but in descending order. A join clause comes in handy here because there is no single data source that contains this information. But join lets us meld the information from the two data sources, and LINQ makes this a snap! In the query expression, I have highlighted the join clause. For each item that the range variable emp references (that is, for each item in employees), it finds the item in the collection empNationalities (represented by the range variable n) where the Id is equivalent to the Id referenced by emp. Then, my projector clause, the select clause, takes data from both collections when building the result and projects that data into an anonymous type. Thus, the result of the query is a single collection where each item from both employees and empNationalities is melded into one. If you execute this example, the results are as shown here:
<pre class="brush:text">
333-33-3333, Ivan Ivanov, Russian

444-44-4444, Vasya Pupkin, Russian
222-22-2222, Spaulding Smails, Irish

111-11-1111, Ed Glasser, American
</pre>
When your query contains a join operation, the compiler converts it to a Join extension method call under the covers unless it is followed by an into clause. If the into clause is present, the compiler uses the GroupJoin extension method which also groups the results. For more information on the more
esoteric things you can do with join and into clauses, reference the MSDN documentation on LINQ or see Pro LINQ: Language Integrated Query in C# 2008 by Joseph C. Rattz, Jr. (Apress, 2007).

There’s no reason you cannot have multiple join clauses within the query to meld data from multiple different collections all at once. In the previous example, you might have a collection that represents languages spoken by each nation, and you could join each item from the empNationalities collection with the items in that language’s spoken collection. To do that, you would simply have one join clause following another.

Source Of Information : Apress Accelerated C Sharp 2010

C# LINQ Keywords - The from Clause and Range Variables

Each query begins with a from clause. The from clause is a generator that also defines the range variable, which is a local variable of sorts used to represent each item of the input collection as the query expression is applied to it. The from clause is just like a foreach construct in the imperative programming style, and the range variable is identical in purpose to the iteration variable in the foreach statement. A query expression might contain more than one from clause. In that case, you have more than one range variable, and it’s analogous to having nested foreach clauses. The next example uses multiple from clauses to generate the multiplication table you might remember from grade school, albeit not in tabular format:
<pre class="brush:csharp">
using System;
using System.Linq;

public class MultTable
{
static void Main() {
var query = from x in Enumerable.Range(0,10)
from y in Enumerable.Range(0,10)
select new {
X = x,
Y = y,
Product = x * y
};
foreach( var item in query ) {
Console.WriteLine( "{0} * {1} = {2}",
item.X,
item.Y,
item.Product );
}
}
}
</pre>
Remember that LINQ expressions are compiled into strongly typed code. So in this example, what is the type of x and what is the type of y? The compiler infers the types of those two range variables based upon the type argument of the IEnumerable<T> interface returned by Range. Because Range returns a type of IEnumerable<int>, the type of x and y is int. Now, you might be wondering what happens if you want to apply a query expression to a collection that only supports the nongeneric IEnumerable interface. In those cases, you must explicitly specify the type of the range variable, as shown here:
<pre class="brush:csharp">
using System;
using System.Linq;
using System.Collections;

public class NonGenericLinq
{
static void Main() {
ArrayList numbers = new ArrayList();
numbers.Add( 1 );
numbers.Add( 2 );
var query = from int n in numbers
select n * 2;
foreach( var item in query ) {
Console.WriteLine( item );
}
}
}
</pre>
You can see where I am explicitly typing the range variable n to type int. At run time, a cast is performed, which could fail with an InvalidCastException. Therefore, it’s best to strive to use the generic, strongly typed IEnumerable<T> rather than IEnumerable so these sorts of errors are caught at compile time rather than run time.

As I’ve emphasized throughout this book, the compiler is your best friend. Use as many of its facilities as possible to catch coding errors at compile time rather than run time. Strongly typed languages such as C# rely upon the compiler to verify the integrity of the operations you perform on the types defined within the code. If you cast away the type and deal with general types such as System.Object rather than the true concrete types of the objects, you are throwing away one of the most powerful capabilities of the compiler. Then, if there is a typebased mistake in your code, and quality assurance does not catch it before it goes out the door, you can bet your customer will let you know about it, in the most abrupt way possible!

<span style="font-size:85%;"><span style="color: rgb(192, 192, 192);">Source Of Information : Apress Accelerated C Sharp 2010</span></span>

Extension Methods and Lambda Expressions Revisited

Before I break down the elements of a LINQ expression in more detail, I want to show you an alternate way of getting the work done. In fact, it’s more or less what the compiler is doing under the covers. The LINQ syntax is very foreign looking in a predominantly imperative language like C#. It’s easy to jump to the conclusion that the C# language underwent massive modifications in order to implement LINQ. Actually, the compiler simply transforms the LINQ expression into a series of extension method calls that accept lambda expressions.

If you look at the System.Linq namespace, you’ll see that there are two interesting static classes full of extension methods: Enumerable and Queryable. Enumerable defines a collection of generic extension methods usable on IEnumerable types, whereas Queryable defines the same collection of generic
extension methods usable on IQueryable types. If you look at the names of those extension methods, you’ll see they have names just like the clauses in query expressions. That’s no accident because the extension methods implement the standard query operators I mentioned in the previous section. In fact, the query expression in the previous example can be replaced with the following code:
<pre class="brush:csharp">
var query = employees
.Where( emp => emp.Salary > 100000 )
.OrderBy( emp => emp.LastName )
.OrderBy( emp => emp.FirstName )
.Select( emp => new {LastName = emp.LastName,
FirstName = emp.FirstName} );
</pre>
Notice that it is simply a chain of extension method calls on IEnumerable, which is implemented by employees. In fact, you could go a step further and flip the statement inside out by removing the extension method syntax and simply call them as static methods, as shown here:
<pre class="brush:csharp">
var query =
Enumerable.Select(
Enumerable.OrderBy(
Enumerable.OrderBy(
Enumerable.Where(
employees, emp => emp.Salary > 100000),
emp => emp.LastName ),
emp => emp.FirstName ),
emp => new {LastName = emp.LastName,
FirstName = emp.FirstName} );
</pre>
But why would you want to do such a thing? I merely show it here for illustration purposes so you know what is actually going on under the covers. Those who are really attached to C# 2.0 anonymous methods could even go one step further and replace the lambda expressions with anonymous methods. Needless to say, the Enumerable and Queryable extension methods are very useful even outside the context of LINQ. And as a matter of fact, some of the functionality provided by the extension methods does not have matching query keywords and therefore can only be used by invoking the extension methods directly.


Source Of Information : Apress Accelerated C Sharp 2010

LINQ Query Expressions

At first glance, LINQ query expressions look a lot like SQL expressions. But make no mistake: LINQ is not SQL. For starters, LINQ is strongly typed. After all, C# is a strongly typed language, and therefore, so is LINQ. The language adds several new keywords for building query expressions. However, their implementation from the compiler standpoint is pretty simple. LINQ query expressions typically get translated into a chain of extension method calls on a sequence or collection. That set of extension methods is clearly defined, and they are called standard query operators.

This LINQ model is quite extensible. If the compiler merely translates query expressions into a series of extension method calls, it follows that you can provide your own implementations of those extension methods. In fact, that is the case. For example, the class System.Linq.Enumerable provides implementations of those methods for LINQ to Objects, whereas System.Linq.Queryable provides implementations of those methods for querying types that implement IQueryable<T> and are commonly used with LINQ to SQL.

This LINQ model is quite extensible. If the compiler merely translates query expressions into a series of extension method calls, it follows that you can provide your own implementations of those extension methods. In fact, that is the case. For example, the class System.Linq.Enumerable provides implementations of those methods for LINQ to Objects, whereas System.Linq.Queryable provides implementations of those methods for querying types that implement IQueryable<T> and are commonly used with LINQ to SQL.

Let’s jump right in and have a look at what queries look like. Consider the following example, in which I create a collection of Employee objects and then perform a simple query:
<pre class="brush:csharp">
using System;
using System.Linq;
using System.Collections.Generic;

public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Decimal Salary { get; set; }
public DateTime StartDate { get; set; }
}

public class SimpleQuery
{
static void Main() {
// Create our database of employees.
var employees = new List<Employee> {

new Employee {
FirstName = "Joe",
LastName = "Bob",
Salary = 94000,
StartDate = DateTime.Parse("1/4/1992") },
new Employee {
FirstName = "Jane",
LastName = "Doe",
Salary = 123000,
StartDate = DateTime.Parse("4/12/1998") },
new Employee {
FirstName = "Milton",
LastName = "Waddams",
Salary = 1000000,
StartDate = DateTime.Parse("12/3/1969") }
};

var query = from employee in employees
where employee.Salary > 100000
orderby employee.LastName, employee.FirstName
select new { LastName = employee.LastName,
FirstName = employee.FirstName };
Console.WriteLine( "Highly paid employees:" );
foreach( var item in query ) {
Console.WriteLine( "{0}, {1}",
item.LastName,
item.FirstName );
}
}
}
</pre>
First of all, you will need to import the System.Linq namespace, as I show in the following section titled "Standard Query Operators." In this example, I marked the query expression in bold to make it stand out. It’s quite shocking if it’s the first time you have seen a LINQ expression! After all, C# is a language that syntactically evolved from C++ and Java, and the LINQ syntax looks nothing like those languages.

Prior to the query expression, I created a simple list of Employee instances just to have some data to work with. Each query expression starts off with a from clause, which declares what’s called a range variable. The from clause in our example is very similar to a foreach statement in that it iterates over the employees collection and stores each item in the collection in the variable employee during each iteration. After the from clause, the query consists of a series of clauses in which we can use various query operators to filter the data represented by the range variable. In my example, I applied a where clause and an orderby clause, as you can see. Finally, the expression closes with select, which is a projection operator. When you perform a projection in the query expression, you are typically creating another collection of information, or a single piece of information, that is a transformed version of the collection iterated by the range variable. In the previous example, I wanted just the first and last names of the employees in my results.

Another thing to note is my use of anonymous types in the select clause. I wanted the query to create a transformation of the original data into a collection of structures, in which each instance contains a FirstName property, a LastName property, and nothing more. Sure, I could have defined such a structure prior to my query and made my select clause instantiate instances of that type, but doing so defeats some of the convenience and expressiveness of the LINQ query. And most importantly, as I’ll detail a little later in the section "The Virtues of Being Lazy," the query expression does not execute at the point the query variable is assigned. Instead, the query variable in this example implements IEnumerable<T>, and the subsequent use of foreach on the query variable produces the end result of the example.

The end result of building the query expression culminates in what’s called a query variable, which is query in this example. Notice that I reference it using an implicitly typed variable. After all, can you imagine what the type of query is? If you are so inclined, you can send query.GetType to the console and you’ll see that the type is as shown here:
<pre class="brush:csharp">
System.Linq.Enumerable+<SelectIterator>d__b`2[Employee, ?
<>f__AnonymousType0`2[System.String,System.String]]
</pre>
For those of you familiar with SQL, the first thing you probably noticed is that the query is backward from what you are used to. In SQL, the select clause is normally the beginning of the expression. There are several reasons why the reversal makes sense in C#. One reason is so that Intellisense will work. In the example, if the select clause appeared first, Intellisense would have a hard time knowing which properties employee provides because it would not even know the type of employee yet.


Source Of Information : Apress Accelerated C Sharp 2010

LINQ: Language Integrated Query

C-style languages (including C#) are imperative in nature, meaning that the emphasis is placed on the state of the system, and changes are made to that state over time. Data acquisition languages such as SQL are functional in nature, meaning that the emphasis is placed on the operation and there is little or no mutable data used during the process. LINQ bridges the gap between the imperative programming style and the functional programming style. LINQ is a huge topic that deserves entire books devoted to it and what you can do with LINQ.1 There are several implementations of LINQ readily available: LINQ to Objects, LINQ to SQL, LINQ to Dataset, LINQ to Entities, and LINQ to XML. I will be focusing on LINQ to Objects because I’ll be able to get the LINQ message across without having to incorporate extra layers and technologies.

LINQ does a very good job of allowing the programmer to focus on the business logic while spending less time coding up the mundane plumbing that is normally associated with data access code. If you have experience building data-aware applications, think about how many times you have found yourself coding up the same type of boilerplate code over and over again. LINQ removes some of that burden.

Development for LINQ started some time ago at Microsoft and was born out of the efforts of Anders Hejlsberg and Peter Golde. The idea was to create a more natural and language-integrated way to access data from within a language such as C#. However, at the same time, it was undesirable to implement it in such a way that it would destabilize the implementation of the C# compiler and become too cumbersome for the language. As it turns out, it made sense to implement some building blocks in the language in order to provide the functionality and expressiveness of LINQ. Thus we have features like lambda expressions, anonymous types, extension methods, and implicitly typed variables. All are excellent features in themselves, but arguably were precipitated by LINQ.


Source Of Information : Apress Accelerated C Sharp 2010


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner