为什么IEnumerable中没有赋值?

Fre*_*ice 0 c# linq-to-xml

我解析一些数据

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

然后我尝试更新一些

foreach (var item in result)
    item.Quantity = 1;
Run Code Online (Sandbox Code Playgroud)

在此之后,我result.Sum(a => a.Quantity)有零...为什么?

Mar*_*zek 5

那是因为result每次开始枚举它时都会再次评估您的集合,因此Sum在新的F130Account对象集上运行,然后foreach循环.这就是LINQ和懒惰的方式.

将结果初始化为List<F130Account>第一个:

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

而这后两者foreachSum将于对象的同一集合运行.