Search code examples
vb.netlinqaveragelinq-group

LinQ Group.Average truncates my values


I've the following table structure:

tempDt

col1 = Product (Integer)  
col2 = Customer (Integer)  
col3 = Center (Integer)  
col4 = Date (Date)  
col5 = Price (Double)  
col6 = Sales (Double)  

This example rows:

1;1;1;01.01.2012;4.39;20000  
1;1;1;02.02.2012;4.46;15000  
1;1;1;03.03.2012;4.22;25000  

And the following Linq Query:

For Each item In From u In tempDT.AsEnumerable
Group u By Product = u("Product"), Customer = u("Customer"), Center = u("Center") Into Group
Select Product, Customer, Center, Price = Group.Average(Function(g) g("Price")), Sales = Math.Round(Group.Sum(Function(g) CDbl(g("Sales"))), 2)

tmpDt.Rows.Add(item.Product, item.Customer, item.Center, item.Price, item.Sales)
Next

But as result I get the following line: 1;1;1;4.0;60000

Group.Average truncates the "Price" column, what's wrong?


Solution

  • It's not clear to me which overload that will pick given that it doesn't know the type at compile-time. You could try:

    Group.Average(Function(g) g.Field(Of Double)("Price"))
    

    If that doesn't help, you should probably double check that the values really aren't truncated before you get to the LINQ query, e.g. while filling the data table.