views:

28

answers:

1

I am trying to AVERAGE 6 different fields on a DataTable, but without grouping. Just the AVERAGE. I have found a couple of examples in C#, but can't find any examples for how to do this in VB. Can someone please help me convert the syntax?

Here is what I have so far:

Dim query = From dtRow In dtIn.AsEnumerable _
                Where dtRow.Field(Of String)("FOLLOWUP") = "Alert" _
                Select New With { _
                    .Brand_Functional_Avg = XXX.Average(Function(f) f("Brand_Functional")), _
                    .Brand_Personal_Avg = XXX.Average(Function(f) f("Brand_Personal")) _
        }

What should I use for XXX? I tried all of the options that I could think of and nothing is compiling.

Trust me, if I could write this in C#, I would, but the project requires VB.

A: 

If you're trying to find the average, you shouldn't be using a select to start with - that's going to create a new result for each row, whereas you want just two results for the whole table. I suggest you do something like:

Dim filtered = From dtRow in dtIn.AsEnumerable _
               Where dtRow.Field(Of String)("FOLLOWUP") = "Alert"

Dim functionalAvg = filtered.Average(Function(f) f("Brand_Functional"))
Dim personalAvg = filtered.Average(Function(f) f("Brand_Personal"))
Jon Skeet
That's what I am doing right now. But I have at least 6 fields to process, maybe more, and was looking for a way to do it in one pass. Is it more efficient to do it in one pass or to call the Average function 6-10 times?
Chris Chubb
LINQ to Objects doesn't really provide a simple way of calculating multiple aggregates in a single pass. If the filter is going to remove a lot of rows, you could call `ToList` on the initial query to compute the results of that once, then iterate over that list 6 times. That's probably the simplest way - I'd try that first and see if it performs well enough for you before going for more complex options.
Jon Skeet