我有以下计算客户帐户状态的运行总计,但是他的第一个值总是添加到自身,我不知道为什么 - 虽然我怀疑我错过了一些明显的东西:
decimal? runningTotal = 0;
IEnumerable<StatementModel> statement = sage.Repository<FDSSLTransactionHistory>()
.Queryable()
.Where(x => x.CustomerAccountNumber == sageAccount)
.OrderBy(x=>x.UniqueReferenceNumber)
.AsEnumerable()
.Select(x => new StatementModel()
{
SLAccountId = x.CustomerAccountNumber,
TransactionReference = x.TransactionReference,
SecondReference = x.SecondReference,
Currency = x.CurrencyCode,
Value = x.GoodsValueInAccountCurrency,
TransactionDate = x.TransactionDate,
TransactionType = x.TransactionType,
TransactionDescription = x.TransactionTypeName,
Status = x.Status,
RunningTotal = (runningTotal += x.GoodsValueInAccountCurrency)
});
Run Code Online (Sandbox Code Playgroud)
哪个输出:
29/02/2012 00:00:00 154.80 309.60
30/04/2012 00:00:00 242.40 552.00
30/04/2012 00:00:00 242.40 794.40
30/04/2012 00:00:00 117.60 912.00
Run Code Online (Sandbox Code Playgroud)
凡309.60
第一排的应该是简单154.80
我做错了什么?
编辑: …
是否有可能foreach
在LINQ(.Select)
)中用lambda表达式替换循环?
List<int> l = {1, 2, 3, 4, 5};
foreach (int i in l)
Console.WriteLine(i);
Run Code Online (Sandbox Code Playgroud)
至:
List<int> l = {1, 2, 3, 4, 5};
l.Select(/* print to console */);
Run Code Online (Sandbox Code Playgroud) 我正在寻找类似 ForEach 方法的方法,但它只在一个元素上运行。
// Do something with every element.
SomeList.ForEach(o => DoSomethingWith(o))
// Do something with just the first element, if any, or nothing at all for an empty list.
SomeLine.ForFirst(o => DoSomethingWith(o))
Run Code Online (Sandbox Code Playgroud)
我试图坚持使用功能范例,并且使用First
, FirstOrOptional
, FirstOrDefault
, 似乎最终涉及大量空检查或异常处理。
Linq 的单行方法是什么?