-1

I would like to convert this DataTable

dt.Columns.Add(new DataColumn("timespan1", typeof(TimeSpan)));
dt.Columns.Add(new DataColumn("timespan2", typeof(TimeSpan)));

into this

dt.Columns.Add(new DataColumn("timespan1", typeof(double)));
dt.Columns.Add(new DataColumn("timespan2", typeof(double)));

I've managed to do it this way.

Double d;        

foreach (DataRow row in dt.Rows)
{
     dr = dtNew.NewRow();

     dr[0] = row.ItemArray[0];
     Double.TryParse(((TimeSpan)(row.ItemArray[1])).TotalMinutes.ToString(), out d);

     dr[1] = d;
     Double.TryParse(((TimeSpan)(row.ItemArray[2])).TotalMinutes.ToString(), out d);

     dr[2] = d;
     dtNew.Rows.InsertAt(dr, 0);
}

Is there any way to use Linq or a lambda expression? I would like to bind this new <double> DataTable to a stacked bar chart. Appreciate your help. Thanks.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
palec
  • 13
  • 5
  • 4
    Why are you converting the TimeSpan to a string and then parsing it? Why not just use `dr[1] = ((TimeSpan) row.ItemArray[1]).TotalMinutes;`? – Jon Skeet Apr 24 '15 at 19:15
  • That really make sense. I'm using TryParse as a safe conversion. – palec Apr 24 '15 at 21:53

1 Answers1

0

What you have right now, is correct except that you should use TotalMinutes directly without converting it to a string, (like Jon Skeet mentioned in the comment).

LINQ is for querying data, it shouldn't be used for modifying the data. Your current code with a foreach loop is clear and conveys the intent.

But if you are looking for LINQ syntax then you can do:

var dummyQuery = dt.AsEnumerable()
                .Select(dr => 
                dtNew.Rows.Add(dr.Field<TimeSpan>("timespan1").TotalMinutes,
                               dr.Field<TimeSpan>("timespan2").TotalMinutes))
                    .ToList();//To Iterate

This will populate the new DataTable, dtNew with TotalMinutes values from both column.

Another option is to project your query result in Select to an anonymous type and then use reflection to create DataTable like Fastest way to fill DataTable from LINQ query using DataContext

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436