开发者

Assigning custom objects to array with a for loop?

G开发者_如何学运维iven 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());
}


Once an array has been created, no new elements can be added. However, you can reassign the elements within it to new objects. If you want new elements (so that your array grows) use (as has been mentioned) the Generic: List<T>. If you want to reassign already existing elements use something like the following (I haven't compiled this, so you may need to make changes:)

for(int i = 0; i < dtable.Rows.Count; i++)
{
    DataRow drow = dtable.Rows[i];
    cars[i] = new car(drow["make"].ToString(), drow["model"].ToString());
}


Arrays cannot be resized in-place.

Instead, you should use a List<Car> and call Add, like this:

 List<car> cars= 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)
 };  //C# 3 collection initializer

for (int i = 0; i < dtable.Rows.Count; i++)
{
    DataRow drow = dtable.Rows[i];
    cars.Add(new car((string)drow["make"], (int)drow["year"]));
}


You could also use LINQ to do this...

var fromTable = from row in dtable.Rows.OfType<DataRow>()
                let make = row["make"] as string
                let year = (int)row["year"]
                select new car(make, year);

car[] arrayOfCars = listOfCars.Concat(fromTable).ToArray();

... If there are tons of Rows in the DataTable and you want to try to squeeze out some performance you could do this instead ...

var makeIndex = dtable.Columns["make"].Ordinal;
var yearIndex = dtable.Columns["year"].Ordinal;

var fromTable = from row in dtable.Rows.OfType<DataRow>()
                let items = row.ItemArray
                let make = items[makeIndex] as string
                let year = (int)items[yearIndex]
                select new car(make, year);


I'd only recommend using an array if you know how many elements you'll have in there total. Otherwise you are better off with a List as Reed and SLaks have suggested.


As said above - use List<Car> to have a list with a dynamic amount of elements - use the method Add(Car item) to add new instances. Make sure to visit the appropriate MSDN site: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

By the way: The operator [] does not work in C#, even if you created an array with e.g. 5 elements and wanted to add the first one.


If you have .NET 3.5, then use Array.Resize().

// 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)
     };    

// resize the array...
var rowCount = dtable.Rows.Count;
var offSet = arrayOfCars.Length;
Array.Resize<car>(ref arrayOfCars, rowCount + offSet);

// populate the new (empty) array elements from the database...
for (int i = 0; i < rowCount; i++)
{
    DataRow drow = dtable.Rows[i];
    arrayOfCars[i + offSet] =  
      new car(drow["make"].ToString(), drow["year"].ToString());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜