Accepted answer

select method

the query represented by this method is not executed until the object is enumerated either by calling its getenumerator method directly or by using foreach in visual c# or for each in visual basic.

so this select is never executed: => dt.rows.add((r as idictionary<string, object>).values.toarray()));



i haven't tested this, but try soemthing like this instead:

data.cast<dictionary<string, object>>().tolist().foreach(x => dt.rows.add(x.values.toarray()));


as sailor already pointed out, linq is lazily evaluated. placing a .lastordefault() on the end of your query will cause execution (because by trying to get the last element it will execute your select()), however it will make your code look even worse!

by definition, linq select should not be used for side-effecting behaviour. i believe you should be able to see that in your question option 2 looks much cleaner than option 1. by reading option 2, i can easily understand, that you are adding each element of data to the datatable. by reading option 1, i'd guess you're doing something to the data variable, which would be wrong.

in conclusion, just stick with option 2. when performance is the same (as this is the case), try to make your code as "easy" to read as possible. a random person should be able to get the general idea without reading through the whole thing.

Related Query

More Query from same tag