这完全是一件简单的事情,并且已经陷入其中一段时间了。以下是方案 - 我在查询中Count
与Group By
进行了对比。然后使用foreach
循环对其进行迭代,如下所示,以获取单个值:
var query = (from c in GetProducts()
group c by c.Type into g
select new
{
Type = g.Key,
Count = g.Count()
});
double value = 0;
double valTotal = 0;
double finalResult = 0;
foreach (var item in query)
{
value = (((Convert.ToDouble(item.Count)) / 10) * 100); //Getting the count from the above query and this gets individual result set, say grouping category
valTotal += value; //Trying to do the total of the 'value' result set and this doesn't return the appropriate sum
finalResult = ((value / valTotal) * 100); Then trying to divide the individual values with the total in the end to get values in percentage
}
示例:从foreach循环和值变量中获取值,我得到 - 10,20,30,40。然后总结它们(10 + 20 + 30 + 40)= 100,最后再将个别结果集合如下(10/100)* 100; (20/100)* 100等。我希望以一种简单的方式做到这一点但似乎错过了一些东西。任何建议都将不胜感激。
注意:finalResult
变量应该最终返回单个结果集(10/100)* 100 = 10%; (20/100)* 100 = 20%。
答案 0 :(得分:2)
列出IGroupings列表,因为我们需要两次:
var query = (from ...).ToList();
然后是百分比列表
decimal sum = query.Sum(g => g.Count);
var percentages = query
.Select(g => (g.Count / sum) * 100) // cast to double/decimal/int as required
.ToList()
;
请注意,这将加起来非常接近100%,但可能会有点偏差。
另外,假设Type == Category
.Select(g => new {
Category = g.Key,
Average = (g.Count / sum) * 100 // cast to double/decimal/int as required
})