LINQ over Datasets or the Bang is back in VB9 by ThinqLinq

LINQ over Datasets or the Bang is back in VB9

One of the features that was added to the May CTP of LINQ was the ability to query over DataSets. There are some minimal methods of manipulating data in existing implementations of the DataSet, including filtering with DataViews, the .Filter method and using DataTable.Select(). If you wanted to work with multiple tables, you needed to use a DataViewManager object. The overview of these options is online on Msdn.

One of the new features of the May CTP of LINQ includes the ability to create queries directly against datasets, including multiple datatables. The preview includes 2 white papers on the subject, one for VB and the other for C#. In order to work with LINQ with datasets, you need to populate the dataset as normal. Assuming you have a dataset (ds) with 2 datatables, Orders and Customers, fill them as usual using the ds.Fill method.

Once you have the data in memory, querying it is a relatively simple task. The first hurdle overcome is the fact that the DataTable does not implement IEnumerable<T>. To solve this, use the .ToQueryable() method as follows on each datatable:

Dim customers = ds.Tables("Customer").ToQueryable()

Dim orders = ds.Tables("Orders").ToQueryable()

Now that we have the results, we should be able to use the standard LINQ querying methods to get a resultset. We can now do the following:

Dim results = From e In Employees _
Select New {FirstName := e.Field(Of String)("FirstName"), _
LastName := e.field(Of String)("LastName")}

In this case we are still dealing with a weakly typed fields collection. (Support does exist for strongly typed datasets, but that's the subject of another post). As a result, we query the field property of the datarow. The field is a generic type which handles the type casting for us. The above code is in essence the same between VB and C#.

As it did with XLINQ, the VB team has included another syntax option for us to simplify the above expression. By returning to the syntax from DAO, we can simplify the .Field("FieldName") syntax to a simple "!" (often referred to as a bang). Thus the above query can be re-written as follows:

Dim results = From e In Employees _
Select New {FirstName := e!FirstName, _
LastName := e!LastName}

While the syntax is indeed simpler, and has precedence from VB prior to .Net, I'm not sure it is a step a forward in the goal of making VB a more English like language rather than using symbolic representations typical of c#. Interestingly, the C# implementation is not implementing the Bang syntax, instead preferring the more verbose .Field<T> syntax. In addition, be aware that the bang syntax still uses late binding as it is just syntactic sugar for the .Fields method.

Do you think VB should bring the bang back? Let me know, or better yet. Tell the team in the LINQ forums.

Posted on - Comment
Categories: LINQ) - VB) -
comments powered by Disqus