Howto iterate over objects stored in one column of a DataTable ----Or howto get an array, collection

G

Gordian

Hello,

I want to iterate over the objects stored in one column of a DataTable.

I can do it the following way:
---------------------------
foreach (DataRow dr in myDataTable)
{
// do something with the data in column 3
string s = dr[2].ToString();
}
---------------------------

But is there another way without the overhead of DataRow / DataTable?
(I assume there is an overhead!)

Perhaps a method, which returns an array of objects stored in one column
of a DataTable.


Greetings
Gordian
 
S

Sahil Malik [MVP]

..NET 1.1 stores DataRows in an Arraylist inside a DataRowCollection.
Iterating through an Arraylist as shown below is not expensive. What is
expensive however is removing objects from an Arraylist - you don't notice
it when the Arraylist is small, but it gets significant as the size of an
Arraylist grows. (and you aren't really removing rows per your code shown
below).

..NET 2.0 doesn't have that problem either. It has a new way of storing such
collections (redblack tree), so removing rows, and methods such as
DataRowCollection.IndexOf become feasible and not so expensive anymore.

The only improvement suggestion I have per your code below, you are
iterating through a number of rows, and setting "string s" to a particular
column - that don't make sense !! :) (string s has a limited scope and gets
overwritten everytime).
If you intended to concatenate to the string, then make sure you use
StringBuilder, not string.

- Sahil Malik [MVP]
ADO.NET 2.0 book -
http://codebetter.com/blogs/sahil.malik/archive/2005/05/13/63199.aspx
 
C

Cor Ligthert [MVP]

Gordion,

I answered you in your other message in the same way as your question is
now, I had not seen it yet.
foreach (DataRow dr in myDataTable)
{
// do something with the data in column 3
string s = dr[2].ToString();
}
---------------------------

How do you think these things are done behind the scene when there is a
method created for you?

I wrote in my other message that in the sample you use above that a For
Index is better (you use in my opinion in this a static
string[JobTable.Rows] s). If you use it like this with the foreach I would
use an arraylist, where you have to add the items.

(Although there is a difference with an inbuilt method because you convert
the object implicitly to String already in your method, what probably gives
you a benefit if you know that it should be a string.

Just my idea

Cor
 
G

Gordian

Hello Sahil,

The code >> string s = dr[2].ToString() << was only dummy code.
But thank you for your explanation about the redblack tree.

Bye
Gordian
 

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