Given this example:
// Create an arary of car objects.
car[] arrayOfCars= new car[]
{
new car("Ford",1992),
new car("Fiat",1988),
new car("Buick",1932),
new car("Ford",1932),
new car("Dodge",1999),
new car("Honda",1977)
};
I tried something like this:
for (int i = 0; i < dtable.Rows.Count; i++)
{
DataRow drow = dtable.Rows[i];
arrayOfCars[] = new car(drow["make"].ToString(), drow["year"].ToString());
}
How do I add additional data to the array while looping through a datatable?
UPDATE1:
I went with the solution proposed by @Reed.
// Create the array, specifying the total length
car[] arrayOfCars = new car[dtable.Rows.Count];
for (int i = 0; i < dtable.Rows.Count; i++)
{
DataRow drow = dtable.Rows[i];
// Assign each car to the specific index within the array (arrayOfCars[i])
arrayOfCars[i] = new car(drow["make"].ToString(), drow["year"].ToString());
}
You can't add elements to an array once it's been created. Instead of using an array, use a List<car>. This will let you call .Add to add elements.
For example:
// Create an List of car objects.
List<car> listOfCars = new List<car>()
{
new car("Ford",1992),
new car("Fiat",1988),
new car("Buick",1932),
new car("Ford",1932),
new car("Dodge",1999),
new car("Honda",1977)
};
You can then do:
for (int i = 0; i < dtable.Rows.Count; i++)
{
DataRow drow = dtable.Rows[i];
listOfCars.Add(new car(drow["make"].ToString(), drow["year"].ToString()));
}
You can use the listOfCars like you would use an array, and access elements by index:
car myCar = listOfCars[3];
If you must have an array, create it after you are done "adding to the list" by calling ToArray() on the list:
// ... Add as above...
car[] arrayOfCars = listOfCars.ToArray(); // Creates an array from your list
Edit:
If you are just trying to allocate and construct your array from your DataTable, and are not going to need to add elements to it after it's constructed, you can use an array, like so:
// Create the array, specifying the total length
car[] arrayOfCars = new car[dtable.Rows.Count];
for (int i = 0; i < dtable.Rows.Count; i++)
{
DataRow drow = dtable.Rows[i];
// Assign each car to the specific index within the array (arrayOfCars[i])
arrayOfCars[i] = new car(drow["make"].ToString(), drow["year"].ToString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With