2014-09-24 7 views
0

確定此代碼是有點元,但它大致說明了我現在如何以及我想實現什麼。Parallel.For日期時間

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

你可以讓一個範圍,並遍歷它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

Parallel.For的所有重載取兩個整數變量作爲開始和結束。我也沒有看到任何支持類似步驟的版本,因此您不能僅使用DateTime的滴答計數作爲循環變量。

但是,當您創建IEnumerable<DateTime>作爲源序列時,應該很容易使用Parallel.ForEach

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

添加+1到count參數如果endDate是包容。

0

好幾天後搜索我覺得如果我把所有的日子放在一個數組中,並通過它「whiled」。它給出了一個相當不錯的結果。代碼易讀

 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();