Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
给定日期数据范围的LINQ和_Linq_C# 4.0 - Fatal编程技术网

给定日期数据范围的LINQ和

给定日期数据范围的LINQ和,linq,c#-4.0,Linq,C# 4.0,给定一个包含一个月数据列表的数据,我需要计算过去两周的总和。我可以在14天内打破清单,然后在7天内计算每个清单的总和 有没有一种优雅的方式来实现上述目标 数据列表的示例如下所示: startDate 2012-05-01 value 1 startDate 2012-05-02 value 1 ........ startDate 2012-05-31 value 1 谢谢。您的意思是要过去两周的总和,还是要过去两周的单个值?后者比前者容易: DateTime end = DateTime

给定一个包含一个月数据列表的数据,我需要计算过去两周的总和。我可以在14天内打破清单,然后在7天内计算每个清单的总和

有没有一种优雅的方式来实现上述目标

数据列表的示例如下所示:

startDate 2012-05-01
value 1

startDate 2012-05-02
value 1
........

startDate 2012-05-31
value 1

谢谢。

您的意思是要过去两周的总和,还是要过去两周的单个值?后者比前者容易:

DateTime end = DateTime.Today;
// Note: inclusive at both ends, so this gives us 14 days in total
DateTime start = end.AddDays(-13);
var sum = data.Where(x => x.StartDate >= start && x.StartDate <= end)
              .Sum(x => x.Value);

在过去的2年里,我一直在追求每一个weeks@nilpun:查看我的编辑。虽然这将是“今天之前7天”意义上的几周,而不是(比如说)“周日到周六”的几周。
DateTime end = DateTime.Today;
// Note: inclusive at both ends, so this gives us 14 days in total
DateTime start = end.AddDays(-13);
var sum = data.OrderBy(x => x.StartDate)
              .Where(x => x.StartDate >= start && x.StartDate <= end)
              .GroupBy(x => ((int) (end - x.StartDate).TotalDays) / 7)
              .Select(g => new { Start = g.First().StartDate,
                                 Sum = g.Sum(x => x.Value) });