2013-06-21 67 views
2

我需要一些幫助來聚合我的集合中的數據。Linq Groupby通過嵌套的可觀察集合

的RrvResponse類

/// <summary> 
    /// The RRV response. 
    /// </summary> 
    public class RrvResponse 
    { 
     /// <summary> 
     /// Initializes a new instance of the <see cref="RrvResponse"/> class. 
     /// </summary> 
     public RrvResponse() 
     { 
      this.BoDPoints = new ObservableCollection<BidOfferPoint>();  
     } 

     /// <summary> 
     /// Gets or sets the id. 
     /// </summary> 
     public string Id { get; set; } 

     /// <summary> 
     /// Gets or sets the message date. 
     /// </summary> 
     public DateTime MessageDate { get; set; } 

     /// <summary> 
     /// Gets or sets the BOD points. 
     /// </summary> 
     public ObservableCollection<BidOfferPoint> BoDPoints { get; set; } 
    } 

實施,

var responses = new ObservableCollection<RrvResponse>(); 

// ....Load responses... 
// ... 
// ... 

響應的次數爲5,所以我有5個的ObservableCollection內響應BoDPoints的。

BOD points are, 

    /// <summary> 
     /// The bid offer point. 
     /// </summary> 
     public class BidOfferPoint 
     { 

      /// <summary> 
      /// Gets or sets the date. 
      /// </summary> 
      public DateTime Date { get; set; } 

      /// <summary> 
      /// Gets or sets the time. 
      /// </summary> 
      public string Time { get; set; } 

      /// <summary> 
      /// Gets or sets the volume. 
      /// </summary> 
      public decimal Volume { get; set; } 

      /// <summary> 
      /// Gets or sets the price. 
      /// </summary> 
      public decimal Price { get; set; } 
     } 

樣品,

Observable Collection Bod - 1 
2013-06-21 
00:00 
100 
10 

2013-06-21 
00:15 
120 
15 

2013-06-21 
00:30 
150 
9 

觀察集合佈德 - 2

2013-06-21 
00:00 
Observable Collection Bod - 1 
2013-06-21 
00:00 
100 
10 

2013-06-21 
00:15 
120 
15 

2013-06-21 
00:30 
150 
9 
40 
1 

2013-06-21 
00:15 
10 
0.5 

2013-06-21 
00:30 
11 
0.1 

觀察集合佈德 - 3

2013-06-15 
00:00 
100 
10 

2013-06-15 
00:15 
120 
15 

2013-06-15 
00:30 
150 
9 

我想按日期然後小時橫跨組收集和彙總卷。因此在上面的例子中,所有21-06-2013小時00:00的數據都應該彙總,21:00-2013小時00:15的所有數據都應該彙總。

什麼是最好的方法使用Linq來做到這一點?

回答

1

您可以使用SelectMany聚集的項目,後來他們組:

var result = responses 
    .SelectMany(r => r.BoDPoints) 
    .GroupBy(p => p.Date) 
    .Select(byDate => 
     new 
     { 
      Date = byDate.Key, 
      EntriesByTime = byDate 
       .GroupBy(p => p.Time) 
       .Select(byTime => 
        new 
        { 
         Time = byTime.Key, 
         TotalVolume = byTime.Sum(p => p.Volume) 
        }) 
     }); 

您可以使用下面的循環(如輸出總體積)

foreach (var byDate in result) 
{ 
    Console.WriteLine("Entries for date " + byDate.Date); 
    foreach (var byTime in byDate.EntriesByTime) 
    { 
     Console.WriteLine("Total volume for time " + byTime.Time + ": " + byTime.TotalVolume); 
    } 
} 
+0

如何獲得總和的數量? –

+0

啊,你想要的總量。見編輯的答案。 –

+0

非常感謝,很有魅力! –