LINQ To DataSet is Really Cool and Makes DataSets More Useful for Demos
by David Hayden ( Florida .NET Developer )
I was working on a demo for a presentation late last night and decided to use a DataTable loaded from an XML File as opposed to a Database for simplicity. One of the things that hit me about 2/3 into the creation of the demo is that querying a DataTable using built-in ADO.NET 2.0 functionality was going to be a bit ugly for my needs. The DataTable searching and filtering functionality in ADO.NET 2.0 is great for simple stuff, but obviously falls short of what you can do using T-SQL. I talk about the support for querying, sorting, and computations built into ADO.NET 2.0 using a DataTable here:
Typed DataSet and Sorting Filtering and Searching a DataTable in ADO.NET - Custom Expressions - ShoppingCart DataSet
As luck would have it two things were with me:
- I am using .NET 3.5 and have LINQ To DataSets
- Pro LINQ by Joseph Rattz fell on my doorstep yesterday :)
Yep, the Gods were shining on me.
Given LINQ To DataSets, one can now do some serious querying against a DataTable, which makes it a lot more useful when doing in-memory querying in demos.
Basically I needed to get a list of distinct countries from the Northwind Customers Table using a DataTable. However, the list returned was to be filtered based on characters enterered into ContactName and CountryName TextBoxes as part of an example of Real-Time Searching / Filtering of a ListView Control as well as AutoComplete Functionality on the UI.
The list of countries can be returned in a couple of lines of code:
IEnumerable<DataRow> seq1 = CustomerTable.AsEnumerable();
return
(from s in seq1
where
s.Field<string>("Country")
.Contains(prefixText)
&&
s.Field<string>("ContactName")
.Contains(contactNameFilter)
select s.Field<string>("Country"))
.Distinct().ToArray();
This wouldn't have been quite as elegant using pure ADO.NET 2.0, although it wouldn't have been impossible either. If it was a typed DataSet, I am sure the query would have been even more elegant. I will be digging into LINQ To DataSet even more now :)