Parallel.For与日期时间

时间:2014-09-24 08:56:39

标签: c# parallel-processing

好的,这段代码有点元,但它大致解释了我现在如何拥有它以及我想要实现的目标。

specialObject{
  DateTime date;
  int number;
}

var startDate = Lowest date in the list;
var endDate = Hightest date int the list;

List<SpecialObject> objs = (list from database where date > startDate and date < endDate)
//A list with alot of dates and numbers, most of the dates are the same. List contains roughly 1000 items, but can be more and less.

for(var date = startDate; date < endDate; date = date.AddDay(1){
    listItem = objs.Where(x => x.Day = date).Sum(x => x.alotOfNUmbers);
}

既然我不在乎我先计算的那天,我想我可以做到这一点。

Parallel.For(startDate, endDate, day => {
     listItem = objs.Where(x => x.Day = date).Sum(x => x.alotOfNUmbers);
}

但我如何让它成为步骤日期?

3 个答案:

答案 0 :(得分:3)

你可以创建一个Range并使用Parallel.ForEach迭代它:

// not tested
var days = Enumerable
     .Range(0, (endDate-startDate).Days)   // check the rounding
     .Select(i => startDate.AddDays(i));

Parallel.ForEach(days, day => ....)

或者,你可以在原始资源上使用PLinq,可能更快。大致是:

 // not tested
 var sums = objs.AsParallel().GroupBy(x => x.date).Select(g => g.Sum(i => i.number));

答案 1 :(得分:1)

Parallel.For的所有重载都有两个整数变量用于开始和结束。我也没有看到任何支持类似步骤的版本,所以你不能只使用DateTime的滴答计数作为循环变量。

但是,当您创建Parallel.ForEach作为源序列时,应该很容易使用IEnumerable<DateTime>

var source = Enumerable.Range(0, (endDate - startDate).Days) 
                       .Select(t => startDate.AddDays(t));

如果count包含在内,则为endDate参数添加+1。

答案 2 :(得分:0)

好几天搜索后,我想我是否把所有的日子放在一个数组中,然后“通过它”。它给出了相当不错的结果。代码易于阅读

        var start = new DateTime(2014, 09, 09);
        var end = new DateTime(2014, 10, 01);

        var listOfDays = new List<DateTime>();

        int i = 0;

        for (var day = start; day < end; day = day.AddDays(1))
        {
            listOfDays.Add(day);
        }

        Parallel.ForEach(listOfDays.ToArray(), currentDay =>
        {
            for (var d = new DateTime(currentDay.Year, currentDay.Month, currentDay.Day, 0, 0, 0); d < new DateTime(currentDay.Year, currentDay.Month, currentDay.Day, 23, 59, 59); d = d.AddSeconds(5))
            {
                var str = "Loop: " + i + ", Date: " + d.ToString();
                Console.WriteLine(str);
            }
            i++;

        });
        Console.Read();