I'm new to using LINQ in VB.Net (within ASP.Net) and I can't seem to figure out how to Sum the data returned in the following query. In my actual code there are 26 items instead of just three and I use a custom class to organize them. I've found countless examples of how to sum a few individual items when selecting them individually but nothing on summing 26 separate columns organized in a class.
我是新手在VB.Net中使用LINQ(在ASP.Net中),我似乎無法弄清楚如何在以下查詢中對返回的數據求和。在我的實際代碼中有26個項而不是只有三個,我使用自定義類來組織它們。我已經找到了無數的例子,說明如何在單獨選擇它們時總結一些單獨的項目,但沒有總結在一個類中組織26個單獨的列。
Edit: Sorry for not being as clear earlier. I am hoping to sum each column. For example if I select 7 days of data rather than 7 rows with item1, item2, and item3 it would just be one row with three columns all being the totals of those rows. Hope that makes sense...
編輯:抱歉沒有早點清楚。我希望對每一欄進行總結。例如,如果我選擇7天的數據而不是7行的item1,item2和item3,那么它只是一行,其中三列都是這些行的總和。希望有道理......
Public Class cQuery
Public Property Item1 As Integer
Public Property Item2 As Integer
Public Property Item3 As Integer
End Class
Dim Query = From data In db.CombinedData
Select New cQuery With {
.Item1 = data.item01,
.Item2 = data.item02,
.Item3 = data.item03
}
UPDATE: So I ended up taking the advice and just using a datatable. I agree, it's a lot easier to work with. Here's what I ended up doing to sum all of the columns. This will take any datatable as an input and spit out a new datatable with an identical structure just with one row containing the summed values of the numeric columns.
更新:所以我最終接受了建議,只使用數據表。我同意,使用起來要容易得多。這就是我最后要做的就是總結所有列。這將把任何數據表作為輸入並吐出一個具有相同結構的新數據表,只有一行包含數字列的總和值。
Public Function SumTableRows(dtInTable As DataTable) As DataTable
Dim dtOutTable As New DataTable
dtOutTable = dtInTable.Clone()
dtOutTable.Rows.Add()
For i As Integer = 0 To dtOutTable.Columns.Count - 1
If IsNumeric(dtInTable.Rows(0).Item(i)) Then
dtOutTable.Rows(0).Item(i) = dtInTable.Compute("Sum(" + dtInTable.Columns(i).ColumnName + ")", "")
End If
Next
Return dtOutTable
End Function
0
Since you seem to be loading the data from a database, a better option would probably be to store the data as a DataTable, rather than a collection of custom class objects. This gives you more options to access the data by row or column.
由於您似乎正在從數據庫加載數據,因此更好的選擇可能是將數據存儲為DataTable,而不是自定義類對象的集合。這為您提供了按行或列訪問數據的更多選項。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/09/18/725df50db4adab7870b662cc2a38c4fa.html。