Linq选择分组依据

本文关键字:选择 Linq | 更新日期: 2023-09-27 17:54:42

我有以下类结构:

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

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

日志日期时间|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)};

Linq选择分组依据

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

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

您应该这样尝试:

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)
        };
    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) 
    }
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方法返回双倍。我希望这将有助于