Writing applications that interact with data sources, such as databases, XML documents, or Web Services such as Flickr or Amazon, is made easier in the .NET Framework 3.5 with the addition of a set of features collectively referred to as LINQ (Language-Integrated Query). In what follows, we start with a very brief overview of LINQ, followed by guidelines for designing APIs in relation to LINQ.

1. A Brief Overview of LINQ

Quite often, programming requires processing over sets of values. Some probably well known examples include: extracting the list of the most recently added books from a database of products; or finding the email address of a person in a directory service such as Active Directory; or transforming parts of an XML document to HTML to allow for web publishing; or something as frequent as looking up a value in a hash table.

LINQ allows for a uniform, language-integrated programming model with data, independent of the technology used to store that data.

2. Extension Methods, Func<>, Action<>, and Expression<>

Extension methods constitute a language feature that allows static methods to be invoked on instance variables. These methods must take at least one parameter, which represents the instance the method is to operate on. For example, in C#, this is done by using the this modifier on such a parameter, when defining the method:

public static bool IsPalindrome(this string s){
//implementation follows here
}

The class that defines such extension methods is referred to in this text as “sponsor” class, and it must be declared as static. To use extension methods, one must import the namespace defining their sponsor class.

Func<> objects represent a generic delegate. For example:
Func divide=(x,y)=>(double)x/(double)y;
Console.WriteLine(divide(2,3));

In this example, divide is a function that takes two integers and returns a double. The last parameter in the generic definition of a Func<> is always the return type. To represent void-returning functions, use Action<> instead.

Expression<> objects represent function definitions that can be compiled and subsequently invoked at runtime. Continuing with our example:

Expression> divideBody=(x,y)=>(double)x/(double)y;
Func divide2=divideBody.Compile();
write(divide2(2,3));

Notice how the syntax for constructing an Expression<> object is very similar to the one used to construct a Func<> object; in fact, the only difference is the static type declaration of the variable (Expression<> instead of Func<>).

source: MSDN

0 comments

Recommended Money Makers

  • Chitika eMiniMalls
  • WidgetBucks
  • Text Link Ads
  • AuctionAds
  • Amazon Associates
blog rating and reviews blogarama - the blog directory blog search directory Bloggeries Blog Directory Top Blog Topsites List website statistics
WebLog Directory Blogging Fusion Bigger Blogger All-Blogs.net directory Easy Seek - Free Search & Directory