雖然我最初認爲它不應該去(簡單地說,因爲你的總和是基於它之前的記錄),但是有一種方法可以繞過它,只需使用返回當前總和的函數並增加一個通過每個新的選擇變量。
不過,我仍然認爲,這應該只計算一次定義的順序,因爲如果用戶想通過名稱或金錢秩序,數額會有所不同,以及
但這裏是一個這樣,如果你願意,你可以做到這一點(我的模擬數據,所以你可能需要做一個小的重構)在C#
Module Module1
Public Class Money
Public Property Name As String
Public Property Money As Decimal
End Class
Function IncreaseMe(ByRef currentSum As Decimal, value As Decimal) As Decimal
currentSum += value
Return currentSum
End Function
Sub Main()
Dim listMoney As New List(Of Money)
Dim total As Decimal = 0
listMoney.Add(New Money With {.Money = 10, .Name = "aaa"})
listMoney.Add(New Money With {.Money = 5, .Name = "bbb"})
listMoney.Add(New Money With {.Money = 15, .Name = "ccc"})
listMoney.Add(New Money With {.Money = 15, .Name = "ddd"})
Dim query = From moneyItem In listMoney
Select New With {.Name = moneyItem.Name, .Money = moneyItem.Money, .Sum = IncreaseMe(total, moneyItem.Money)}
For Each queryItem In query
Console.WriteLine("{0}{3}{1}{3}{2}", queryItem.Name, queryItem.Money, queryItem.Sum, vbTab)
Next
Console.WriteLine("Total money: {0}", total)
Console.ReadLine()
End Sub
End Module
它甚至更容易一些,那裏你可以簡單地增加局部變量和結果然後加到總和上
static void Main(string[] args)
{
IList<MoneyTable> money = new List<MoneyTable>();
money.Add(new MoneyTable { Money = 10, Name = "aaa" });
money.Add(new MoneyTable { Money = 5, Name = "bbb" });
money.Add(new MoneyTable { Money = 15, Name = "ccc" });
money.Add(new MoneyTable { Money = 15, Name = "ddd" });
decimal totalSum = 0;
var query = from m in money
select new { Name = m.Name, Money = m.Money, Sum = (totalSum = totalSum + m.Money) };
Console.WriteLine("{0}\t{1}\t{2}", "Name", "Money", "Sum");
foreach (var item in query)
{
Console.WriteLine("{0}\t{1}\t{2}", item.Name, item.Money, item.Sum);
}
Console.ReadLine();
}
「它不工作」不適合我。 – 2015-04-04 13:05:03
@ SamAxe:你能幫我嗎? – 2015-04-04 13:07:19