views:

53

answers:

1

Hi Guys, I have a DataTable like this,

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

I need a fast logic to convert the data into this format

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

Please help me to find any sample code or any advice is highly appreciated.

Thanks

+1  A: 
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;
}
Timwi
After looking at your code, I got really depressed !. All this time I thought I knew C# well. But your code, just blew me away. Thank you very much for the sample code. really appreciated
kakopappa
Glad to be of help. :) If there is any particular aspect that you would like help with, please feel free to ask. I realise there aren’t many comments in there...
Timwi