LINQ查询在日期范围内的Sum值

时间:2013-03-23 11:06:45

标签: c# linq

我正在尝试创建一个linq查询,该查询将生成一个日期范围的集合,其中包含容量值的总和,该值可以覆盖范围可以重叠的帐户,并且我希望该重叠期间的总和和不同的日期范围。感谢。

public ActionResult Index()
        {
            List<Capacities> _list = new List<Capacities>{
               new Capacities {StartDate = DateTime.Parse("01/01/2013"), StopDate = DateTime.Parse("01/01/2013 06:00"), Capacity = 100},
               new Capacities {StartDate = DateTime.Parse("01/01/2013 04:00"), StopDate = DateTime.Parse("01/02/2013 00:00"), Capacity = 120},
               new Capacities {StartDate = DateTime.Parse("01/04/2013"), StopDate = DateTime.Parse("01/04/2013 15:00"), Capacity = 100},
               new Capacities {StartDate = DateTime.Parse("01/04/2013 15:00"), StopDate = DateTime.Parse("01/04/2013 18:00"), Capacity = 150}
            };
            //results expected
            //01/01/2013 00:00 - 01/01/2013 04:00   100
            //01/01/2013 04:00 - 01/01/2013 06:00   220
            //01/01/2013 06:00 - 01/02/2013 00:00   120
            //01/04/2013 00:00 - 01/04/2013 15:00   100
            //01/04/2013 15:00 - 01/04/2013 18:00   150
            return View();
        }

        public class Capacities
        {
            public DateTime StartDate { get; set; }
            public DateTime StopDate { get; set; }
            public int  Capacity {get;set;}
        }

1 个答案:

答案 0 :(得分:3)

我做了一些编程,但是我扩展了你的代码。但我最终能够使用LINQ: - )

我的代码:

SortedSet<DateTime> splitdates = new SortedSet<DateTime>();
foreach (var item in _list)
{
    splitdates.Add(item.Period.Start);
    splitdates.Add(item.Period.End);
}

var list = splitdates.ToList();
var ranges = new List<DateRange>();
for (int i = 0; i < list.Count - 1; i++)
    ranges.Add(new DateRange() { Start = list[i], End = list[i + 1] });

var result = from range in ranges
             from c in _list
             where c.Period.Intersect(range) != null
             group c by range into r
             select new Capacities(r.Key.Start, r.Key.End, r.Sum(a => a.Capacity));

完整代码在此处:http://pastebin.com/wazbb1r3 请注意,输出因区域设置而异。此外,有些位不像DateRange.Contains()。

在上面的两个循环中,我不知道如何以可读的方式将它们转换为LINQ。