如何在Linq查询中获得分组结果的平均值

时间:2016-11-29 00:37:47

标签: c# linq

我有一个linq查询,可以获得前12个月的评分:

var ratingsByMonth =
    from month in Enumerable.Range(0, 12)
    let key = new { Year = DateTime.Now.AddMonths(-month).Year, Month = DateTime.Now.AddMonths(-month).Month }
    join groupedRating in ratings on key
            equals new
            {
                groupedRating.RatingDate.Year,
                groupedRating.RatingDate.Month
            } into g
    select new {
        Date = key,
        Rating = g.Select(x=>x.Rating)
    };

ratingsByMonth从我的数据集中返回以下JSON:

{Date: {Year: 2016, Month: 11}, Rating: [4]}
{Date: {Year: 2016, Month: 10}, Rating: [5, 5, 4]}
{Date: {Year: 2016, Month: 9}, Rating: []}
{Date: {Year: 2016, Month: 8}, Rating: []}
{Date: {Year: 2016, Month: 7}, Rating: []}
{Date: {Year: 2016, Month: 6}, Rating: []}
{Date: {Year: 2016, Month: 5}, Rating: []}
{Date: {Year: 2016, Month: 4}, Rating: []}
{Date: {Year: 2016, Month: 3}, Rating: []}
{Date: {Year: 2016, Month: 2}, Rating: []}
{Date: {Year: 2016, Month: 1}, Rating: []}
{Date: {Year: 2015, Month: 12}, Rating: []}

但是我试图将评级字段汇总为平均值。我试过这个:

return Json(new
{
    Average = ratingsByMonth.Average(x=>x.Rating),
    Dates = ratingsByMonth.Select(x => Date)
});

但是我在平均线上突出显示以下错误:

  

无法隐式转换类型   ' System.Collections.Generic.IEnumerable'到了很长时间?'

我正在寻找的输出是:

{Date: {Year: 2016, Month: 11}, Rating: 4}
{Date: {Year: 2016, Month: 10}, Rating: 3.5}
{Date: {Year: 2016, Month: 9}, Rating: 0}
{Date: {Year: 2016, Month: 8}, Rating: 0}
{Date: {Year: 2016, Month: 7}, Rating: 0}
{Date: {Year: 2016, Month: 6}, Rating: 0}
{Date: {Year: 2016, Month: 5}, Rating: 0}
{Date: {Year: 2016, Month: 4}, Rating: 0}
{Date: {Year: 2016, Month: 3}, Rating: 0}
{Date: {Year: 2016, Month: 2}, Rating: 0}
{Date: {Year: 2016, Month: 1}, Rating: 0}
{Date: {Year: 2015, Month: 12}, Rating: 0}

编辑:

尝试更改为以下内容:

return Json(new
{
    Average = ratingsByMonth.Select(x => x.Rating).SelectMany(x => x).Average(),
    Dates = ratingsByMonth.Select(x => x.Date.Month)
});

然而,这只是给了我一个平均值'整个数据集中的值,而不是每个日期的平均值。

编辑:

以下是示例数据:

RatingID    Rating  RatingDate
5           5   2016-10-09 20:11:29.590
11          0   2016-10-09 20:14:42.503
21          5   2016-10-09 20:24:15.667
60          4   2016-10-28 11:01:21.220
64          4   2016-11-03 16:30:47.657

所以十一月的平均值应该是4,十月应该是3.5(5 + 0 + 5 + 4/4)

2 个答案:

答案 0 :(得分:1)

在原始查询中,您可能希望这样做。

//other code removed for brevity
select new {
    Date = key,
    Rating = g.Count() > 0 ? g.Average(x => x.Rating) : 0
};

然后返回结果

return Json(ratingsByMonth);

答案 1 :(得分:0)

这里的问题是,属性评级本身就是一个序列,而不是您可以要求平均方法考虑的离散值。

听起来你实际上想做的事情是:将所有评级集合展平为一个序列,然后取得所有结果值的平均值。

类似的东西:

var avg = ratingsByMonth.Select(x => x.Rating).SelectMany(x => x).Average()

这使用Select生成一系列Rating数组。 SelectMany然后展平列表,之后你可以取平均值。