I am trying to fill my datatable using LINQ expression below , this works fine but feels like a hack. Is there a better way to do this ?
var Records = <Dictionary object with some data.>
DataTable objDataTable = null;
objDataTable.Columns.Add("Column1", typeof (string));
objDataTable.Columns.Add("Column2", typeof (string));
// Have to perform .Count() to execute the linq expression in order to
// add datarows in datatable
Records.Keys.Select(rec => objDataTable.Rows.Add(new object[] {rec, Records[rec]})).Count();
As you can see above I have to to .Count() at the end in order to execute the statement. Earlier I was doing .ToArray() but then I thought .Count() would be cheaper.
Either way this does not feel very readable.
Yes – just use a
foreachloop which is perfectly readable and suited for this:Just because you can use Linq does not mean you should always be compelled to do so – especially if you have code with side effects.