I don't fully understand the first loop. If you have a set of Department items, why then duplicate all of them into a DataTable at all? You're effectively just making a second copy of each into memory, and if there are a lot of them, that will be a problem. It's also a waste of processing time.
I'd be far more inclined to do something like this (untested, uncompiled pseudocode):
var cmd = new SqlCeCommand(connection);
cmd.CommandText = "MyTableName";
cmd.CommandType = CommandType.TableDirect
using(var rs = cmd.ExecuteResultSet(
ResultSetOptions.Updatable | ResultSetOptions.Scrollable))
{
foreach(var dept in depts)
{
var record = rs.CreateRecord();
record.SetInt(0, dept.ID);
// do other fields
rs.Insert(record);
}
}
We're doing better because:
- We're not duplicating records
- We're not effectively iterating the data set twice
- We're going table direct