Hi, folks – this is an update to my CoDe Magazine article on LINQ, which appeared in the July/August 2007 issue.
First, I've posted an updated version of the .NET project, based on the released version of Visual Studio 2008:
http://www.commongroundsolutions.net/crashcourseonlinq.zip
Second, I've been doing a community presentation on LINQ, and have added several pieces of code since the publication of the CoDe article. In many cases, the additions come from great suggestions and feedback from attendees.
First, one of the code samples showed how to pump the results of a LINQ query, from an IEnumerable into a List collection:
List<VendorResults> oListResults = new List<VendorResults>();
foreach (VendorResults oRec in oVendorResultsEnumerable)
oListResults.Add(oRec);
Well, Mark Lindell from the Baltimore MSDN User Group pointed out that one of the overloads for the List constructor allows someone to specify an IEnumerable. Therefore, I didn't need to write code to iterate through the IEnumerable, and can do the following instead:
List<VendorResults> oListResults =
new List<VendorResults>(oVendorResults);
Thanks Mark!
Second, Manoj K. Srivastava from Central Maryland CodeCamp asked about a streaming LINQ to XML example. My example read an entire XML file into memory, and Manoj asked me how to handle an XML file that would be too big to load into memory. So I've added a second example in the download project for handling a streaming XML example. Thanks to my friend Don Demsak for pointing me in the right direction on this one (which I've attributed in the download code). Thanks for the idea, Manoj!
Third, I was getting some runtime errors when doing LINQ to SQL queries where I was bringing back null results. So I've added nullable type references, like so:
var OrderSum = from Vendor in db.Purchasing_Vendor
orderby Vendor.Name
select new {
Vendor.Name,
TotFreight = Vendor.Purchasing_PurchaseOrderHeader.Sum
(o => (decimal?) o.Freight),
TotSubTot = Vendor.Purchasing_PurchaseOrderHeader.Sum
(o => (decimal?) o.SubTotal)
};
I intend to make more updates to this download project.
My goal (maybe an ambitious one) is to provide a single download project with as many meaningful LINQ code samples as possible. Right now, the download project features the following:
- 3 LINQ to SQL examples
- 7 standard LINQ queries to demonstrate LINQ syntax
- A generic extension method to convert an anonymous type to an ADO.NET DataTable
- An example for executing a LINQ query into an IEnumerable/List
- 2 LINQ to XML examples
- 2 LINQ to DataSet examples (one untyped, one typed)
- 1 LINQ to Object example
- Several examples of Lambda expressions and extension methods.
If you have any suggestions, feel free to let me know.
KG