我有下面的代码在LINQ的GroupBy选择设置属性:尝试使用循环
public class Report
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Sales { get; set; }
}
var result = myItems.GroupBy(x => new { Id = x.Id, Name = x.Name }).Select(x => new Report { Id = x.Key.Id, Name = x.Key.Name });
foreach (var item in result)
{
item.Sales = anotherColletion.FirstOrDefault(x => x.Id == item.Id).Sales;
}
我不能销售产权这种方式设置为任意值。即使我尝试:
foreach (var item in result)
{
item.Sales = 50;
}
不过,如果我使用下面的代码它的工作原理设置属性:
var result = myItems.GroupBy(x => new { Id = x.Id, Name = x.Name }).Select(x => new Report { Id = x.Key.Id, Name = x.Key.Name, Sales = 50 });
设计是这样吗?
如果我先执行myItems.ToList(),然后在没有ToList()的情况下执行GroupBy(),那么这样做还是会导致查询重新执行? – Thomas
@Thomas:这应该在技术上有效,因为可变的Report报告对象已经在该阶段创建并实现了。只有分组才会重新执行,而不是创建对象。我强烈建议不要这样做。 – Ani
我将实现myItems.ToList()的原因是因为我想对集合执行多个GroupBy(未包括在此问题中),并使用这些集合进行计算。我的推理是运行一个数据库查询,然后在另一个GroupBy中使用内存集合。请问为什么你不推荐这样做? – Thomas