2010-09-16 50 views
0

我有這樣一個DataTable,C#的數據處理邏輯的幫助

AccessDateTime   | Direction 
2010-09-15 12:12:49 | IN 
2010-09-15 12:36:03 | OUT 
2010-09-15 12:53:05 | IN 
2010-09-15 14:04:19 | OUT 
2010-09-15 14:17:35 | IN 
2010-09-15 16:07:57 | OUT 
2010-09-15 16:10:57 | OUT 
2010-09-15 18:43:18 | OUT 

我需要一個快速的邏輯將數據轉換成這種格式

Date  | In Time | Out Time 
2010-09-15 12:12:49 | 12:36:03 
2010-09-15 12:53:05 | 14:04:19 
2010-09-15 14:17:35 | 16:07:57 
2010-09-15 N/A  | 16:07:57 
2010-09-15 N/A  | 16:10:57 
2010-09-15 N/A  | 18:43:18 

請幫我找到任何示例代碼或任何建議是高度讚賞。

感謝

+0

你怎麼知道的12時36分03秒OutTime是關係到12點12分49秒銀泰是能夠涉及在一起? – InSane 2010-09-16 08:20:35

+0

但爲什麼遺傳算法? – nan 2010-09-16 08:22:38

+0

如果它是一個In,有一個Out並且它是按時間順序決定的。所以在這種情況下,根據這個假設它需要計算。順便說一句,這是門入口出口程序。謝謝。 – kakopappa 2010-09-16 08:24:37

回答

1
DataTable output = new DataTable(); 

using (var e = dataTable.AsEnumerable().GetEnumerator()) 
{ 
    if (!e.MoveNext()) 
     // No data in the datatable at all 
     return; 

    // Get first row 
    var dt = (DateTime) e.Current["AccessDateTime"]; 
    var row = ((Direction) e.Current["Direction"] == Direction.In) 
     ? new { Date = dt.Date, InTime = (TimeSpan?) dt.TimeOfDay, OutTime = (TimeSpan?) null } 
     : new { Date = dt.Date, InTime = (TimeSpan?) null, OutTime = (TimeSpan?) dt.TimeOfDay }; 
    DataRow newRow; 

    // Look at all the other rows 
    while (e.MoveNext()) 
    { 
     dt = (DateTime) e.Current["AccessDateTime"]; 
     if ((Direction) e.Current["Direction"] == Direction.Out && row.OutTime == null) 
     { 
      row = new { Date = row.Date, InTime = row.InTime, OutTime = (TimeSpan?) dt.TimeOfDay }; 
      continue; 
     } 

     newRow = output.NewRow(); 
     newRow["Date"] = row.Date; 
     newRow["InTime"] = row.InTime; 
     newRow["OutTime"] = row.OutTime; 
     row = new { Date = dt.Date, InTime = (TimeSpan?) dt.TimeOfDay, OutTime = (TimeSpan?) null }; 
    } 

    newRow = output.NewRow(); 
    newRow["Date"] = row.Date; 
    newRow["InTime"] = row.InTime; 
    newRow["OutTime"] = row.OutTime; 
} 
+0

看完你的代碼後,我非常沮喪!這一次我以爲我很瞭解C#。但是你的代碼,只是把我吹走了。非常感謝您的示例代碼。非常感謝 – kakopappa 2010-09-16 09:40:30

+0

很高興能有所幫助。 :)如果您有任何特別的方面需要幫助,請隨時詢問。我意識到那裏沒有太多評論...... – Timwi 2010-09-16 09:57:15