【问题标题】:How can I get percentage in LINQ?如何在 LINQ 中获得百分比?
【发布时间】:2021-01-09 01:07:13
【问题描述】:

我的问题是:我怎样才能把它翻译成 LINQ?

select Reasons.Description, count(*) * 100.0 / sum(count(*)) over() AS Porcentage
from Rejected
iNNER JOIN Reasons
ON Rejected.Reason = Reasons.ReasonID
group by Reasons.Description

或者如果我想使用存储过程,我如何用这个结果填充 Ilist。

我想要做的只是以数字形式获取每个“描述类型”的百分比,以便稍后填写圆环图。

谢谢

【问题讨论】:

  • 你在使用实体框架吗?
  • 我不会将其设为 CTE,而是使用嵌套查询来获取分组计数,并使用外部查询将其转换为百分比。那会更容易翻译成 Linq to Entities,我什至不确定是否可以翻译 CTE。
  • 是使用实体框架
  • @Igor 说得通。

标签: sql linq


【解决方案1】:

我建议从您的数据存储中获取原始计数,然后在应用层计算百分比,或者让您的图表组件根据该原始值确定百分比。像这样的东西应该可以工作:

var query = (from reason in dc.Reasons
            join reject in dc.Rejections on reason.ReasonID equals reject.Reason
            group reason by reason.Description into grouped
            select new { Reason = grouped.Key, ItemCount = grouped.Count() })
            .ToList(); 

// If you really need to generate the averages and not let your charting component figure the percentages out for you:
var totalItems = query.Sum(q => q.ItemCount);
var averages = query.Select(q => new { q.Reason, Average = q.ItemCount / totalItems * 100});

如果您更喜欢 lambdas 而不是查询语法,请查看 GroupJoin。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 2012-02-11
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多