如何计算后修改集合?

时间:2014-02-27 15:04:35

标签: c# asp.net-mvc linq collections lambda

我有一个执行某些报告的方法,如下所示:

 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);

我在ToListCollectionforeach ...所有内容上尝试了forloop

我做错了什么?

修改

这是视图模型

 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; }
 }

解决方案:

我的问题是我使用Every(automapper扩展 - 出错)而不是ToList集合,然后使用ForEach,现在我的字段正在正确填充。

感谢您指出正确的方向。

2 个答案:

答案 0 :(得分:2)

当您打算执行浮点除法时,您正在进行整数除法。您的计数除以totalViews然后截断为int将等于0

首先将一个相关数字投放到double

views.Each(v=>v.PercentageOfViews = v.TotalViewsForCountry / (double)totalViews * 100);

答案 1 :(得分:1)

问题是整数除法。变化

v.TotalViewsForCountry / totalViews * 100

100.0 * v.TotalViewsForCountry / totalViews