473,657 Members | 2,507 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Datareader to Array best practice?

Hey All,

I have question about the best way to go about doint this:
SqlDataReader _dr=components. getItems();
fooclass _myarray = new fooclass[5]; //create new array of my class
int i=0;

while (_dr.Read()) //loop through data reader to add items to the array
{
_myarray[i]=new myarray();
_myarray[i].title=_dr["sometitle"].ToString();
_myarray[i].description=_d r["somedescriptio n"].ToString();
i++;
}
_dr.Close();

Since I don't know how large the datareader will be until I loop through it
what is the best way to manage the size of this array? Is it most efficient
to check if the my array is full and the allocate another N spaces in it?

Thanks alot,

-a newb trying to improve


Nov 17 '05 #1
7 36915

"Cory Toms" wrote...
I have question about the best way to go about doint this:
SqlDataReader _dr=components. getItems();
fooclass _myarray = new fooclass[5]; //create new array of my class
int i=0;

while (_dr.Read()) //loop through data reader to add items to the array
{
_myarray[i]=new myarray();
_myarray[i].title=_dr["sometitle"].ToString();
_myarray[i].description=_d r["somedescriptio n"].ToString();
i++;
}
_dr.Close();

Since I don't know how large the datareader will be until I
loop through it what is the best way to manage the size of
this array? Is it most efficient to check if the my array
is full and the allocate another N spaces in it?


Well, I'm sure there are even better ways than this, but it should at least
be "better":

SqlDataReader _dr = components.getI tems();
ArrayList _myFoos = new ArrayList(); // use a dynamic Collection
FooClass _item = null;

while (_dr.Read()) //loop through data reader to add items to the array
{
_item = new FooClass();
_item.title=_dr["sometitle"].ToString();
_item.descripti on=_dr["somedescriptio n"].ToString();
_myFoos.Add(ite m);
}
_dr.Close();

There are also methods for extracting the references in "array" form from an
ArrayList, if you really need to.

// Bjorn A

I have never really understood the need to prefix variables with "_", and I
still don't... ;-)
Nov 17 '05 #2
Yes, I agree with Bjorn. Because you cannot know in advance the number
of items in a data reader as you can with data set, you should make use
of an array list and call ArrayList.ToStr ing to get the array if that
is what you want.
Example:
return (FooClass[]) _myFoos.ToArray (typeof(FooClas s));

Nov 17 '05 #3
>you cannot know in advance the number of items in a data reader

Well, you can, but it is admittedly kinda ugly. If you call a select
count(...) in your sql before the actual data you retrieve as a compound
query (for lack of a better term), SQL Server will return 2 resultsets back.
A data reader can access each result set returned, so you read the first
result set consisting of a single row which containts the count, and then
process the second.
"Truong Hong Thi" <th*****@gmail. com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Yes, I agree with Bjorn. Because you cannot know in advance the number
of items in a data reader as you can with data set, you should make use
of an array list and call ArrayList.ToStr ing to get the array if that
is what you want.
Example:
return (FooClass[]) _myFoos.ToArray (typeof(FooClas s));

Nov 17 '05 #4
I'm new to C#. Is there a preferred way to take the rows out of the
DataReader? I see I can use sqlDataReader.G etValues(object[]), or I can
iterate through each column of each row.

Any comments on the preferred method?

Thank you for your time,
tberry

"Truong Hong Thi" wrote:
Yes, I agree with Bjorn. Because you cannot know in advance the number
of items in a data reader as you can with data set, you should make use
of an array list and call ArrayList.ToStr ing to get the array if that
is what you want.
Example:
return (FooClass[]) _myFoos.ToArray (typeof(FooClas s));

Nov 17 '05 #5

"ASP Yaboh" wrote...
I'm new to C#. Is there a preferred way to take the
rows out of the DataReader? I see I can use
sqlDataReader.G etValues(object[]), or I can
iterate through each column of each row.

Any comments on the preferred method?


I would rather say there *is* no "preferred" way in this case.

It depends on how you will make use on the data after you've read it from
the database.

In most cases I've encountered, a row corresponds to an instance of a
defined class, which you have to "populate" somehow, much as in my previous
example:

ArrayList myFoos = new ArrayList();
FooClass item = null;

while (dr.Read())
{
item = new FooClass();
item.field1 = dr["field1"];
item.field2 = dr["field2"];
myFoos.Add(item );
}
dr.Close();

....but as I said, it all depends on how you actually design your
application.

// Bjorn A
Nov 17 '05 #6
Thank you

"Bjorn Abelli" wrote:

"ASP Yaboh" wrote...
I'm new to C#. Is there a preferred way to take the
rows out of the DataReader? I see I can use
sqlDataReader.G etValues(object[]), or I can
iterate through each column of each row.

Any comments on the preferred method?


I would rather say there *is* no "preferred" way in this case.

It depends on how you will make use on the data after you've read it from
the database.

In most cases I've encountered, a row corresponds to an instance of a
defined class, which you have to "populate" somehow, much as in my previous
example:

ArrayList myFoos = new ArrayList();
FooClass item = null;

while (dr.Read())
{
item = new FooClass();
item.field1 = dr["field1"];
item.field2 = dr["field2"];
myFoos.Add(item );
}
dr.Close();

....but as I said, it all depends on how you actually design your
application.

// Bjorn A

Nov 17 '05 #7
Reg

"Bjorn Abelli" <bj**********@D oNotSpam.hotmai l.com> wrote in message
news:e7******** ******@tk2msftn gp13.phx.gbl...

"Cory Toms" wrote...
I have question about the best way to go about doint this:
SqlDataReader _dr=components. getItems();
fooclass _myarray = new fooclass[5]; //create new array of my class
int i=0;

while (_dr.Read()) //loop through data reader to add items to the array
{
_myarray[i]=new myarray();
_myarray[i].title=_dr["sometitle"].ToString();
_myarray[i].description=_d r["somedescriptio n"].ToString();
i++;
}
_dr.Close();

Since I don't know how large the datareader will be until I
loop through it what is the best way to manage the size of
this array? Is it most efficient to check if the my array
is full and the allocate another N spaces in it?
Well, I'm sure there are even better ways than this, but it should at

least be "better":

SqlDataReader _dr = components.getI tems();
ArrayList _myFoos = new ArrayList(); // use a dynamic Collection
FooClass _item = null;

while (_dr.Read()) //loop through data reader to add items to the array
{
_item = new FooClass();
_item.title=_dr["sometitle"].ToString();
_item.descripti on=_dr["somedescriptio n"].ToString();
_myFoos.Add(ite m);
}
_dr.Close();

There are also methods for extracting the references in "array" form from an ArrayList, if you really need to.

// Bjorn A

I have never really understood the need to prefix variables with "_", and I still don't... ;-)


Thanks for the help, that worked well.

I also don't understand the "_"'s, but thats the way things go when you
inherit code.

Nov 17 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
8655
by: Dave O | last post by:
Is it possible to return a SQLdatareader from a web service?
7
4008
by: DS | last post by:
Is there a way to automatically close the data reader connection? I'm using the MS Data Access Application block to substantially {entirely} separate the data access layer (DAL) from the business layer (BL) and this is great with DataSets since they can be closed off in the DAL, but it doesn't seem possible with the DataReader since it would need to be .close() in the BL once I'm done with it. I've read on the web that there is a bit of...
14
2233
by: Bihn | last post by:
I was reading about datareader which is said to be slimmer & faster then dataset. Since the datareader have to go fetching the dat from the database every time it need it, the data it gets then should be up to date. However, both the IbuySpy and Duwamish samples and most, if not all, the shopping cart sample codes I've seen use dataset to implement the opration for ecommerce sites. So is the trip that the datareader need to go fetch the...
1
3087
by: Brent | last post by:
I'm having a hard time wrapping my head around how to build a multi-dimensional array of n length out of a DataReader loop. Take this pseudo-code: ======================================= public string get_array(string sql) { //create db connection & open
7
2903
by: Diffident | last post by:
Hello All, I would like to use DataReader based accessing in my Data Access Layer (DAL). What is considered to be a best practice while returning from a DAL method that executes a query and returns N rows. DataReader object? Collection object? DataTable object? Returning a DataReader object is not a good practice...right? Thnks for all your suggestions!!
272
14008
by: Peter Olcott | last post by:
http://groups.google.com/group/comp.lang.c++/msg/a9092f0f6c9bf13a I think that the operator() member function does not work correctly, does anyone else know how to make a template for making two dimensional arrays from std::vectors ??? I want to use normal Array Syntax.
10
6095
by: jimmy | last post by:
Hi again, sorry for posting two questions so close together but im working on a school project which is due in soon and running into some difficulties implementing the database parts. I have the code below which when executed generates the following error message: 'There is already an open datareader with this command which must be closed first' Private Sub MainMenu_Load(ByVal sender As System.Object, ByVal e As
2
2382
by: =?Utf-8?B?ZGJhMTIz?= | last post by:
Note, I'm using C# I am wondering what type of control I should use for iterating through the set of records returned by callin this method below, so that I can then do some stuff with each record like string manipulation, or taking the data for insertion into another table, etc.. Here's the function that returns the data as an ArrayList. Note: You'll see plain S and B since for this post, I wanted to keep our
3
2209
by: Froefel | last post by:
Hi group I am creating a web application that uses a simple DAL as an ObjectDataSource. To retrieve data from the database, I use a DataReader object from which I then assign the various fields to properties in an object, like so: in the DB, the fields are defined as follows: ProjectID int NOT NULL
0
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8825
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7324
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1953
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1611
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.