transfer data from Dictionary to DataTable

J

John A Grandy

I need to transfer the data from one data-structure to another :

data-structure 1 : Dictionary<DateTime,decimal?> dataDictionary = new
Dictionary<DateTime,decimal?> ();


data-structure 2 :

DataTable dataTable = new DataTable();
dataTable.Columns.Add( "Col1", typeof( DateTime ) );
dataTable.Columns.Add( "Col2", typeof( decimal ) );


null values in data-structure 1 should be represented as DBNull.Value in
data-structure 2


Currently, I am transferring the data via iteration :



foreach ( KeyValuePair<DateTime, decimal?> data in seriesData )
{
if ( data.Value.HasValue )
{
dataTable.Rows.Add( new object[] { data.Key, data.Value } );
}
else
{
dataTable.Rows.Add( new object[] { data.Key, DBNull.Value } );
}



Is there a faster technique ?

Thanks.
 
P

Peter Duniho

[...]
foreach ( KeyValuePair<DateTime, decimal?> data in seriesData )
{
if ( data.Value.HasValue )
{
dataTable.Rows.Add( new object[] { data.Key, data.Value } );
}
else
{
dataTable.Rows.Add( new object[] { data.Key, DBNull.Value } );
}



Is there a faster technique ?

Why do you ask? Is this a bottleneck that is causing performance problems
in your code?

I suspect that you could in fact speed up the process at least a little.
Things like calling DataTable.BeginInit()/EndInit() around the update,
setting the MinimumCapacity property to the size of your input, or maybe
there's even some performance value in using IDataReader with the Load()
method to shift from a "push" data model to a "pull" data model for
initialization (though that would surprise me, you never know until you
try! :) ), these all might help a little.

But the simple loop you've posted seems just fine to me. At most, I might
invert the conditional and operation, so there's a single call to
"dataTable.Rows.Add()", but the second object in the array you pass is
"data.Value.HasValue ? data.Value : DBNull.Value". But even that as
almost entirely a stylistic change, unlikely to affect performance in a
noticeable way.

I'd say that unless you've found this section of code to be causing a
performance problem that affects the end-user, you should leave it nice
and simple, just the way it is.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top