【发布时间】:2014-03-31 02:38:00
【问题描述】:
我有一个方法可以执行一些报告,如下所示:
var views = people.Viewers
.GroupBy(v => new { v.Viewer.Country, v.Viewer.Gender })
.Select(v =>
new StatisticViewModel
{
Country = v.Key.Country,
Females = v.Count(r => r.Viewer.Gender.Equals(false)),
Males = v.Count(r => r.Viewer.Gender.Equals(true)),
TotalViewsForCountry = v.Count()
//I will calculate this bad guy after I have all the info:
//PercentageOfViews = xxxxx
});
现在我有一个视图集合,但是我还有一个属性要计算,即该国家/地区的视图百分比,这是我的问题所在,我尝试了很多方法,例如:
//Total number of Views
var totalViews = views.Sum(v=>v.TotalViewsForCountry);
//When I return this to my view the property is 0!
views.Each(v=>v.PercentageOfViews = v.TotalViewsForCountry / totalViews * 100);
我在Collection、foreach、forloop 上尝试了ToList... 一切。
我做错了什么?
编辑
这是视图模型
public class StatisticViewModel
{
public int Id { get; set; }
public string Country { get; set; }
public int Females { get; set;}
public int Males { get; set; }
public int TotalViewsForCountry { get; set; }
public double PercentageOfViews { get; set; }
}
解决方案:
我的问题是我使用 Each(自动映射器扩展 - 错误)而不是 ToList 集合,然后使用 ForEach,现在我的字段已正确填充。
感谢您指出正确的方向。
【问题讨论】:
-
@NicoSchertler 每个都是 linq 函数,System.Linq 对集合的每个元素执行操作。查看 ViewModel 的更新。
-
不,它不是 LINQ 函数。 LINQ 特别是为查询而设计的,而不是为了改变集合或引起副作用。
-
你说得对,这是一个 Automapper 扩展方法而不是集合。我的错。
标签: c# asp.net-mvc linq collections lambda