Linq Select Group By

时间:2013-01-19 19:41:38

标签: c# linq group-by

我有以下类结构:

public class PriceLog
{
   public DateTime LogDateTime {get; set;}
   public int Price {get; set;}
}

对于列表< PriceLog> 我想要一个Linq查询来生成一个输出,该输出等同于下面表示的数据:

LogDateTime | AVG(价格)
2012年1月| 2000
2012年2月| 3000

简单地说:我想计算一年中每个月的平均价格 注意:LogDateTime属性应格式为LogDateTime.ToString("MMM yyyy")

我尝试过以下操作,但不确定它是否会产生所需的结果:

var result = from priceLog in PriceLogList
                         group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
                         select new PriceLog { GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), SilverPrice = (int)dateGroup.Average(p => p.SilverPrice)};

4 个答案:

答案 0 :(得分:20)

这将为您提供一系列匿名对象,包含日期字符串和两个平均价格的属性:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new { 
               LogDate = g.Key,
               AvgGoldPrice = (int)g.Average(x => x.GoldPrice), 
               AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
            };

如果您需要获取PriceLog对象列表:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new PriceLog { 
               LogDateTime = DateTime.Parse(g.Key),
               GoldPrice = (int)g.Average(x => x.GoldPrice), 
               SilverPrice = (int)g.Average(x => x.SilverPrice)
            };

答案 1 :(得分:3)

    from p in PriceLog
    group p by p.LogDateTime.ToString("MMM") into g
    select new 
    { 
        LogDate = g.Key.ToString("MMM yyyy"),
        GoldPrice = (int)dateGroup.Average(p => p.GoldPrice), 
        SilverPrice = (int)dateGroup.Average(p => p.SilverPrice) 
    }

答案 2 :(得分:3)

你应该这样试试:

var result =
        from priceLog in PriceLogList
        group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
        select new {
            LogDateTime = dateGroup.Key,
            AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
        };

答案 3 :(得分:1)

var result = priceLog.GroupBy(s => s.LogDateTime.ToString("MMM yyyy")).Select(grp => new PriceLog() { LogDateTime = Convert.ToDateTime(grp.Key), Price = (int)grp.Average(p => p.Price) }).ToList();

我已将其转换为int,因为我的Price字段为int而Average方法返回double。我希望这会有所帮助