按日历周对结果进行分组并获得平均值

时间:2015-03-04 08:20:59

标签: c# linq

我有一个数据集如下

Name  Start Date    End Date   Percentage
  A    1/1/2015    31/3/2015      50
  B    1/1/2015    30/6/2015      100
  C    1/4/2015    30/6/2015      50

我想按日历周对此数据集进行分组,并且需要获得平均百分比 结果如下

Year   Week    Average
 2015    1       ---
 2015    2       ---

获得此结果的最佳linq查询是什么。我试过以下代码。但价值不正确

var grouped = result.Select(p =>
                        new
                        {
                            Week = CultureInfo.InvariantCulture.Calendar.GetWeekOfYear
                                                 (p.StartDate, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday),
                            Year = p.StartDate.Year,
                            EndDate = p.EndDate,
                            percentage = p.percentage
                        })
                        .GroupBy(x => new { x.Year, x.Week })
                        .OrderBy(x=>x.Key.Year).ThenBy(x=>x.Key.Week)
                        .Select((g, i) => new
                        {
                            g.Key.Year,
                            g.Key.Week,
                            Sum = g.Average(t => t.percentage)
                        });

1 个答案:

答案 0 :(得分:0)

public class Program
{   
    public static void Main()
    {
        var input = new List<P>
        {
            new P { StartDate = new DateTime(2015, 1, 1), EndDate = new DateTime(2015, 3, 31), Week = DayOfWeek.Monday, Year = 2015, percentage = 50 },
            new P { StartDate = new DateTime(2015, 1, 1), EndDate = new DateTime(2015, 6, 30), Week = DayOfWeek.Monday, Year = 2015, percentage = 100 },
            new P { StartDate = new DateTime(2015, 4, 1), EndDate = new DateTime(2015, 6, 30), Week = DayOfWeek.Monday, Year = 2015, percentage = 50 },
        };  

        var result = input.SelectMany(p => 
        {
            var weeks = Enumerable.Range(0, (p.EndDate - p.StartDate).Days / 7)
                                  .Select(i => CultureInfo.InvariantCulture.Calendar.AddWeeks(p.StartDate, i))
                                  .Select(i => CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(i, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday));

            return weeks.Select(w => new { Week = w, Percentage = p.percentage / weeks.Count() });
        })
        .GroupBy(x => x.Week)
        .Select(g => new { Week = g.Key, Average = g.Average(t => t.Percentage) });
    }
}

public class P
{
    public DateTime StartDate;
    public DateTime EndDate;
    public DayOfWeek Week;
    public int Year;
    public double percentage;
}

我还没有在这里使用过Year,但是你可以得到这个想法并自己添加年份。