views:

919

answers:

1

Given a datatable, I wish to output an IEnumerable type (dictionary(of T) would be perfect, otherwise a datatable would be acceptable) that provides an aggregation of the data within the datatable.

In SQL I would write the query as such:

select groupByColumn, sum(someNumber) from myTable group by groupByColumn

In VB.NET the closest I have got to this (achieved using information here) is:

' dt is a datatable containing two columns, referred to by index in p below
Dim q = From p In dt Group p By p(0) Into Sum(p(1)) Select p(0), SumOfNumber = Sum

However I receive error: "Range variable name can be inferred only from a simple or qualified name with no arguments." on the p(0) element.

Therefore my question is as follows:

  1. How can I resolve this error?
  2. How do I process the result (q) as an IEnumerable type?

Life isn't made any easier because I'm using Linq in unfamiliar vb.net. Many examples are in C#, but I haven't really come across anything suitable even in C#.

A: 

Resolved: I had to alias the columns returned.

Dim q = From p In dt
    Group p By transactionTypeName = p(0) _
    Into totalForType = Sum(Convert.ToDouble(p(1))) _
    Select transactionTypeName, totalForType

Also note that I had to do a conversion on the value that I was summing because being a dynamically returned datatable didn't have the column type specified.

Hint found here because vb.net oh so helpfully gives us a different error message to C#'s "Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access."

For completeness, results are processed as below:

For Each item In q ' no need for defining item as a type (in C# we'd use the var keyword)
    If item.totalForType = magicNumber Then
     'do something
    Else
     'do something else
    End If
Next
Topdown
There is a ToDictonary extension method, as in q.ToDictionary...
AMissico