2014-01-30 66 views
0

#集合操縱我在這個格式c。與LINQ的

IList<ReportRow> MyCollection 

凡ReportRow是

Dictionary<string, object> 

所以MyCollection的可能是這樣一個集合:

Id1 Id2 Value Status Entered 
    123 2 56  New  50:01.7 
    123 2 76  Old  50:23.0 
    123 2 12  New  50:23.0 
    127 3 54  Old  50:23.0 
    127 3 77  New  59:23.0 

...

Linq t有沒有辦法帽子我可以做到這一點: 我需要做的是爲每個Id1 + Id2組合我需要輸出值狀態是新的和狀態是舊的。對於Id1 + Id2組合,可能會有多個New值,因此它應該選取最新的New記錄,並使用Entered列進行排序。

新的記錄將包含所有的記錄加1額外的列像這樣:

Id1 Id2 NewValue OldValue Entered 
    123 2 12   76   50:23.0 
    127 3 77   54   59:23.0 

任何幫助,這將是巨大的

+0

當它是'Dictionary '時,ReportRow'如何包含5個值(Id1,Id2,Value,Status,Entered)? –

+0

你可以發佈實體類嗎?或者到目前爲止使用的Linq代碼片段。 –

回答

0

這應該這樣做(或靠近,因爲這是我的頭頂)

collection.OrderByDescending(r => r.Value.Entered) 
      .GroupBy(r => {r.Id1, r.Id2) 
      .Select(g => new { 
       Id1 = g.Key.Id1, 
       Id2 = g.Key.Id2, 
       NewValue = g.FirstOrDefault(v => v.Status == "New").Value ?? 0, 
       OldValue = g.FirstOrDefault(v => v.Status == "Old").Value ?? 0, 
       Entered = g.Last().Entered 
      }) 

如果你不關心字典字符串鍵你可以做

collection.SelectMany(d => d.Value) 
      .OrderByDescending(r => r.Value.Entered) 
      .GroupBy(rr => {rr.Value.Id1, rr.Value.Id2) 
      .Select(g => new { 
       Id1 = g.Key.Id1, 
       Id2 = g.Key.Id2, 
       NewValue = g.FirstOrDefault(v => v.Status == "New").Value ?? 0, 
       OldValue = g.FirstOrDefault(v => v.Status == "Old").Value ?? 0, 
       Entered = g.Last().Entered 
      }) 
0
from row in MyCollection 
group row by new { row.Id1, row.Id2 } into g 
let lastNew = g.OrderByDescending(r => r.Entered) 
       .FirstOrDefault(r => r.Status == "New") 
let lastOld = g.OrderByDescending(r => r.Entered) 
       .FirstOrDefault(r => r.Status == "Old") 
select new { 
    Id1 = g.Key.Id1, 
    Id2 = g.Key.Id2, 
    NewValue = (lastNew == null) ? null : (int?)lastNew.Value, 
    OldValue = (lastOld == null) ? null : (int?)lastOld.Value, 
    Entered = g.OrderByDescending(r => r.Entered).First().Entered 
}