The previous installment in this article series, Extension Methods, Implicitly Typed Variables, and Object
Initializers, examined three new features to the C# 3.0 and Visual Basic 9 languages that allow for developers to use LINQ's standard query operators and providers to
write SQL-like query syntax to work with common data stores. But extension methods, implicitly typed variables, and object initializers are only part of the story. Two additional
language features - lambda expressions and anonymous types - are also essential ingredients in LINQ's unique syntax.
Recall that LINQ's standard query operators can work with any collection of data that implements the IEnumerable<T> interface. Some of the standard query
operators perform rather straightforward operations on the collection; the Count standard query operator, for instance, simply returns the number of elements
in the collection. However, other standard query operators are more flexible, allowing the page developer to dictate how the operator will work. The Where standard query
operator is such an example - it filters the elements in the collection based on a developer-specified filtering method. But just how can a developer "pass" a method to theWhere standard query operator as an input parameter? The .NET Framework has long supported the notion of delegates, which are type-safe function pointers. However,
the syntax for delegates is a little confusing and verbose. Lambda expressions offer a much more terse syntax for defining an anonymous method.
Anonymous types allow for inline types. In a nutshell, anonymous types let you clump a set of values together into a new type without having to first declare the type
via a class. For example, imagine that you have a collection of Employee objects, where each Employee object has properties like Name, Salary, HireDate, and so on. You may want to apply some filtering condition on this collection using the Where standard query operator and
then project the collection of Employee objects into a collection of objects that includes just the Name and Salary properties.
With anonymous types this style of projection is straightforward and natural. Without anonymous types you would first have to create a class like EmployeeSimplified
that contained only those two properties of interest.
This article provides an overview of lambda expressions and anonymous types. These two language enhancements, along with extension methods, implicitly typed variables, and object
initializers, are what allows for LINQ's query syntax. Read on to learn more!
Read More >
0 comments:
Post a Comment