在我的dal中,它循環遍歷數據表中的每個對象,然後應用於我的對象類。我希望能夠做的是在它傳遞到我的對象類之前檢查先前傳遞的行是否具有相同的產品代碼。例如;循環訪問DAL中的數據
當前數據行是;
ProductCode quantity
100001 500
如果上一行傳遞的數據具有相同的產品代碼;
ProductCode quantity
100001 500
它會增加數量與前行,使1000
如果不相同的產品代碼,然後只是把它應用到我的對象類爲正常
在我的dal中,它循環遍歷數據表中的每個對象,然後應用於我的對象類。我希望能夠做的是在它傳遞到我的對象類之前檢查先前傳遞的行是否具有相同的產品代碼。例如;循環訪問DAL中的數據
當前數據行是;
ProductCode quantity
100001 500
如果上一行傳遞的數據具有相同的產品代碼;
ProductCode quantity
100001 500
它會增加數量與前行,使1000
如果不相同的產品代碼,然後只是把它應用到我的對象類爲正常
所以,你要running total在DataTable
?你可以使用LINQ:
var runningTotalsPerCode = table.AsEnumerable()
.Select(row => new
{
ProductCode = row.Field<int>("ProductCode"),
Quantity = row.Field<int>("Quantity"),
AllFields = row.ItemArray
})
.GroupBy(x => x.ProductCode) // group by the product-code
.SelectMany(g => g. // flatten the group after the running-total was calculated
Select((x, index) => new
{
x.ProductCode,
x.Quantity,
x.AllFields,
RunningTotal = g.Take(index + 1).Sum(xx => xx.Quantity)
}));
然後你就可以循環它來創建一個新的DataTable
或值傳遞給你的對象。
編輯:哎呦,我只是注意到你想要VB.NET。給我幾分鐘....
Dim codeGroups = From row In table
Let ProductCode = row.Field(Of Int32)("ProductCode")
Let Quantity = row.Field(Of Int32)("Quantity")
Let Code = New With {ProductCode, Quantity, .AllFields = row.ItemArray}
Group Code By Code.ProductCode Into CodeGroup = Group
Dim runningTotalsPerCode = codeGroups.
SelectMany(Function(g) g.CodeGroup.Select(Function(x, index) New With
{
g.ProductCode,
x.Quantity,
x.AllFields,
.RunningTotal = g.CodeGroup.Take(index + 1).Sum(Function(xx) xx.Quantity)
}))
這個樣本數據快速測試:
Dim table As New DataTable()
table.Columns.Add("ProductCode", GetType(Int32))
table.Columns.Add("Quantity", GetType(Int32))
table.Rows.Add(555555, 777) ' other group
table.Rows.Add(100001, 500)
table.Rows.Add(100001, 444)
table.Rows.Add(100001, 442)
ProductCode=555555, Quantity=777, AllFields={Length=2}, RunningTotal=777 <anonymous type>
ProductCode=100001, Quantity=500, AllFields={Length=2}, RunningTotal=500 <anonymous type>
ProductCode=100001, Quantity=444, AllFields={Length=2}, RunningTotal=944 <anonymous type>
ProductCode=100001, Quantity=442, AllFields={Length=2}, RunningTotal=1386 <anonymous type>
只要保持先前創建的業務對象的引用。如果前一個目標代碼等於當前代碼,則將該信息組合到前一個目標中。
取決於數據量和業務邏輯的完成方式。這可以在你的循環之後完成。當所有的業務對象都被創建並插入列表中時。您可以將一個函數添加到列表中,以組合相似的產品代碼。
更好的選擇是在數據庫中完成所有這些操作,並讓查詢返回所需的內容。