Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

The Baker's Dozen: A 13-Step Crash Course for Using LINQ : Page 5

Start becoming familiar with the different areas of LINQ with the Microsoft Visual Studio "Orcas" Beta.


advertisement
Tip 11: LINQ to Objects
Continuing on the theme of Tip 10, you can use the same LINQ syntax from previous tips to query a collection. This emphasizes one of the key points of LINQ: using similar (not always identical, but similar) syntax to query all sorts of different objects:

// Query a customer collection var NewResult = from oRecs in oCustomerRecs where ((oRecs.LocationID==1 || oRecs.LocationID==2) && oRecs.AmountDue > 15000) orderby oRecs.LocationID ascending, oRecs.AmountDue descending select oRecs; foreach (CustomerRec oRec in NewResult) MessageBox.Show(oRec.LocationID.ToString() + ", " + oRec.AmountDue.ToString());

Tip 12: Language Features for C# 3.0
The C# 3.0 language in Orcas Beta 1 contains several new features to increase developer productivity. Here's a quick run-through of some new language capabilities.

Remember to add a reference to System.Data.Linq (or whichever LINQ namespace is appropriate for your project).
Automatic properties allow you to create a property without having to declare a private field. For example, prior to C# 3.0, you'd normally write the following code to create properties for FirstName and LastName:

public class Employee // Prior to C# 3.0 { private string _FirstName; public string FirstName { get { return _FirstName; } set { _FirstName = value; } } private string _LastName; public string LastName { get { return _LastName; } set { _LastName = value; } } }

In C# 3.0 you can create the same class and properties, but with less code.

Author's Note: Important: you must declare both get and set methods when you use anonymous properties. You will not be able to use anonymous properties if you only declare a get accessor (for read-only properties).



public class Employee // Now in C# 3.0 { public string FirstName { get; set; } public string LastName { get; set; } }

C# 3.0 contains object and collection initializers that let you set initial properties for the class or members of a list, without requiring a constructor.

Employee oEmployee = new Employee{FirstName = "Kevin", LastName = "Goff"}; List<Employee> oEmployees = new List<Employee>() { new Employee{FirstName = "Kevin", LastName = "Goff"}, new Employee{FirstName = "Steve", LastName = "Goff"}};

Implicitly-typed variables let you declare a variable without explicitly setting a type. The new var keyword represents an anonymous type, a type inference, as follows:

var Name = "Kevin S. Goff"; var Sum = 0; // Implicitly-typed array var IntArry = new [] {10,20,30,40}; foreach(var intValue in IntArry) Sum += intvalue;

Next, C# 3.0 provides the capability of using extension methods. Extension methods can be a little difficult to understand initially. Think of the way extender classes work in .NET today: they (extender classes) allow you to append (extend) properties and capabilities to an existing class, as opposed to creating a subclass and recompiling. Extension methods let you add static methods to an existing .NET type—without even touching the original type. They are beneficial when it is difficult or not possible to add instance methods to an existing class.

Listing 4 (from Tip 6) showed an example of an extension method (ToADOTable) that you can use for any object that implements IEnumerable. The method becomes available in IntelliSense for any corresponding type. Extension methods are a powerful capability for extending .NET Framework functionality. Note the this IEnumerable<T> varlist syntax in the first parameter; this essentially means that any object that resides in the current namespace and implements IEnumerable can use the method ToADOTable.

public static DataTable ToADOTable<T>( this IEnumerable<T> varlist, CreateRowDelegate<T> fn)

Finally, lambda expressions are a "kinder, gentler" form of anonymous methods. C# 2.0 introduced anonymous methods to allow developers to insert code blocks inline, in place of a delegate. While anonymous methods are powerful, their syntax tends to be a little complex (see the example back in Tip 9 for supplying an anonymous method for the List class Sort method).

Lambda expressions perform the same functionality with more concise code, by using the token set symbol (=>) to separate the parameter list from the expression, as opposed to specifying the delegate statement and parameter type. Behind the scenes, the compiler translates the lambda expression into delegate-based code. As you saw back in Tip 9, you can specify multiple parameters in the lambda expression simply by delimiting them with a comma (parm1, parm2 =>), and then using them accordingly in the expression itself.

// VS2005 syntax oCustomerRecs.FindAll( (delegate(CustomerRec oRec) { return (oRec.LocationID == 1); })); // Lambda expression, more concise oCustomerRecs.FindAll( oRec => oRec.LocationID == 1 );

The code in the lambda expression can include C# 3.0 code as well as LINQ query expression code.

Tip 13: Language Features for VB 9.0
VB developers will be happy to hear that all of the C# 3.0 language features described in the preceding tip (automatic properties, object and collection initializers, implicitly-typed variables, extension methods, and lambda expressions) are also available with the version of VB 9 included with Orcas Beta 1. In addition, VB 9.0 also supports nullable types and relaxed delegates. The latter are helpful in instances where method signatures do not need to match, such as sender and argument declarations for a button click.

Resources, Resources, Resources
Do you ever feel like you're on information overload, and yet you simultaneously worry that there are more resources out there of which you're not aware? Every few weeks I take the time to add to and organize my list of blogs, sites, and articles. You won't have a problem finding resources on LINQ and Orcas Beta 1. Many people and companies are already writing valuable blogs on LINQ and Orcas Beta 1.

The most important link is Microsoft's home site for the LINQ project, but here are some others you may find useful:

Additionally, Microsoft has a site with download links for a large number of samples and demo code:

Although I didn't cover them in this article, there are two other LINQ-related projects worth mentioning. One is PLINQ, a special implementation of LINQ designed to run on multiple processors. The other is BLINQ, an ASP.NET project to generate data-driven Web sites. Just use Google to search for more on these topics.

You can download the source code for this article from my Web site. Check my blog for follow-up tips and notes on Baker's Dozen articles…and maybe a few additional treats!



Kevin S. Goff is the founder and principal consultant of Common Ground Solutions, a consulting group that provides custom web and desktop software solutions in .NET, Visual FoxPro, SQL Server, and Crystal Reports. Kevin has been building software applications for 17 years. He has received several awards from the U.S. Department of Agriculture for systems automation. He has also received special citations from Fortune 500 companies for solutions that yielded six-figure returns on investment. He has worked in such industries as insurance, accounting, public health, real estate, publishing, advertising, manufacturing, finance, consumer packaged goods, and trade promotion. In addition, Kevin provides many forms of custom training.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap