0

我解析一些数据

var result = xml.Descendants("record").Select(x => new F130Account
    {
        Account = x.Descendants("Account").First().Value,
    });

然后我尝试一些更新

foreach (var item in result)
    item.Quantity = 1;

在这之后我result.Sum(a => a.Quantity)是零......为什么?

4

1 回答 1

5

那是因为result每次开始枚举时都会再次评估您的集合,因此Sum在新的F130Account对象集上运行,然后foreach循环不同。这就是 LINQ 及其惰性的工作方式。

将结果初始化为List<F130Account>first:

var result = xml.Descendants("record").Select(x => new F130Account
    {
        Account = x.Descendants("Account").First().Value,
    }).ToList();

之后,两者都foreachSum在同一个对象集合上运行。

于 2013-04-02T09:27:48.510 回答