ICollection <t>使用LINQ </t>计算每小时的平均值

时间:2013-09-27 20:27:28

标签: c# linq

对于以下场景,我如何使用LINQ来获得每小时和每天的平均值:

public class Sales
{
    public Sales()
    {

    }

    public string Name { get; set;}
    public DateTime SaleDate { get; set;}
    public int Price { get; set;}           
}

ICollection<Sales> myCollection = new List<Sales>();

我知道我可以从myCollection获得这样的平均值:

double average = myCollection.Average(a => a.Price);

我需要的是获得每天的平均值:

date         average
24.09.2013   1243
25.09.2013   1278
26.09.2013   2587

然后是特定日期的平均每小时:

hours              average
00:00 - 01:00      125
01:00 - 02:00      127
02:00 - 03:00      158

依此类推......

3 个答案:

答案 0 :(得分:6)

你可以通过以下日期做平均值:

var results = myCollection.GroupBy(i => i.SaleDate.Date)
                          .Select(g => new {Date = g.Key, Average = g.Average(a => a.Price) });

foreach(var result in results)
{
       Console.WriteLine("{0}  {1}", result.Date, result.Average);
}

在给定日期按小时计算:

var results = myCollection.Where(i => i.SaleDate.Date == theDate)
                          .GroupBy(i => i.SaleDate.Hour)
                          .Select(g => new {Hour = g.Key, Average = g.Average(a => a.Price) });

foreach(var result in results)
{
   var hourStart = TimeSpan.FromHours(result.Hour);
   var hourEnd = TimeSpan.FromHours(result.Hour + 1);
   Console.WriteLine("{0:hh\:mm} - {1:hh\:mm}  {1}", hourStart, hourEnd, result.Average);
}

答案 1 :(得分:3)

每天的平均值可以通过以下方式完成:

var average = myCollection.GroupBy(item => item.SaleDate.Date)
                  .Select(item2 => new 
                  { 
                      Date = item2.Key, 
                      Average = item2.Average(a => a.Price) 
                  });

平均每小时可以通过以下方式完成:

var average2 = myCollection.GroupBy(item => new 
               { 
                   Date = item.SaleDate.Date, 
                   Hour = item.SaleDate.Hour,
                   DateTime = item.SaleDate })
                       .Select(item2 => new 
                       { 
                           Date = item2.Key.DateTime, 
                           Average = item2.Average(a => a.Price) 
                       });

答案 2 :(得分:3)

按日期

var results = myCollection
                .GroupBy(i => i.SaleDate.Date)
                .Select(x => new { Date = x.Key, Avg = x.Average(y => y.Price)});

按日期和小时计算平均值:

var results = myCollection
                .GroupBy(item => new {
                             Date = item.SaleDate.Date, 
                             Hour = item.SaleDate.Hour
                })
                .Select(x => new {
                             Date = x.Key.Date,
                             Hour = x.Key.Hour,
                             Avvg = x.Average(a => a.Price)
                });