C# 3.0 Features - C# 3.0 Examples - Query Expressions - Anonymous Types - Lamba Expressions - Extension Methods
by David Hayden ( Microsoft MVP C# ), C# 3.0 Tutorials and Features
Awhile back I talked about Extension Methods in C# 3.0 and how LINQ uses them to provide additional methods to classes implementing IEnumerable<T> for querying purposes.
Hence, you can use LINQ, for example, to query a class of List<Customer> because List<T> implements IEnumerable<T>. Let's mind walk through this :)
Automatically Implemented Properties ( Compiler Feature )
Creating a Customer Class using Automatically Implemented Properties in the Orcas C# 3.0 Compiler gives you the following code:
public class Customer {
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public Customer() {}
}
Object and Collection Initializers
You can then use the new C# 3.0 Collection and Object Initializers to create the List<Customer> class:
List<Customer> listOfCustomers =
new List<Customer> {
{ Id = 1, Name="Dave", City="Sarasota" },
{ Id = 2, Name="John", City="Tampa" },
{ Id = 3, Name="Abe", City="Miami" }
};
Query Expressions
And then you can query the list of customers using query expressions:
var query =
from c in listOfCustomers
where c.City == "Sarasota"
select new {c.Name,c.City};
Implicity Typed Local Variables and Anonymous Types
Pulling apart the query expression above shows us a couple of new features in C# 3.0:
Query Expression Translation
But, as I mentioned before, this is just a bit of syntatic sugar, because the query expression gets translated using Query Expression Translation into extension methods that are invoked behind the scenes. The .Where and .Select Methods are extension methods of IEnumerable<T>:
var query = listOfCustomers
.Where(c => c.City.Equals("Sarasota"))
.Select(c => new {c.Name, c.City});
Lambda Expressions
Lambda Expressions are shown above to ease the pain of typing the very verbose anonymous delegates:
c => c.City.Equals("Sarasota")
avoids
delegate(Customer c) {
return c.City.Equals("Sarasota");
}
Extension Methods
As with all Extension Methods, they are sitting somewhere in a static class as static methods. In this case, System.Query.Sequence. The above can also be written as:
var query = Sequence
.Where(listOfCustomers, c => c.City == "Sarasota")
.Select(c =>new { c.Name, c.City });
Query Execution
And, of course, this query does not execute until it is enumerated:
var sarasotaCustomers = query.ToList();
Conclusion
Hopefully this provides useful :)
Source: David Hayden ( Microsoft MVP C# ), C# 3.0 Tutorials and Features