LinQ Group.Average truncates my values
-
12-06-2021 - |
Domanda
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?
Soluzione
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.
Altri suggerimenti
Your query is rather unreadable, have a look at my changes(e.g. using the strong type DataRow.Field
extension method):
Dim groups = From u In tempDT.AsEnumerable
Group u By Key = New With {
.Product = u.Field(Of Integer)("Product"),
.Customer = u.Field(Of Integer)("Customer"),
.Center = u.Field(Of Integer)("Center")
} Into PCCroup = Group
Select New With {
.PCC = Key,
.Price = PCCroup.Average(Function(u) u.Field(Of Double)("Price")),
.Sales = Math.Round(PCCroup.Average(Function(u) u.Field(Of Double)("Sales")), 2)
}
For Each item In groups
tmpDt.Rows.Add(item.PCC.Product, item.PCC.Customer, item.PCC.Center, item.Price, item.Sales)
Next
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow