Reputation: 385
I have an array with properties that i want to transfer to a list using a for loop
.
for (int i = 0; i < data.cars.Count; i++)
{
var model = data.cars[i].model.ToString();
cars = new List<Car>
{
new Car { Model = model }
};
}
Keep getting a System.ArgumentOutOfRangeException:Index was out of range
exception. Not sure how to insert each model name in a new Car
instance using a for loop
.
EDIT:
data.Count
was a typo, the same exception was thrown while using data.cars.Count
. To clarify, the length of data.cars.Count
is 20 objects containing a model
property.
Upvotes: 1
Views: 2232
Reputation: 216293
Probably you could remove this loop and use a single linq line
var cars = data.cars.Select(x => new Car{ Model = x.model}).ToList();
Your actual code triggers the mentioned exception because whatever data.Count is, it is not equal to the number of elements in the cars collection. If data.Count is bigger than the numbers of element in the data.cars collection then the exception occurs.
However you have another logical error in your code, at each loop your code creates a new List containing a single Car element. At each loop your code assigns this list to the external variable cars. Of course, when the loop exits, you have your external variable cars assigned to a list with just the last element in the loop.
If you prefer a standard loop approach then you could write
List<Car> cars = new List<Car>();
foreach (var car in data.cars)
{
cars.Add(new Car { Model = car.model });
}
Upvotes: 8
Reputation: 8852
You are getting that exception because number of data records may be higher than number of cars in each data. For example data may be a collection of 10 items but cars collection in each data record may only contain one or two elements. So, first, second and third iteration may work just fine but after that you'll get an exception.
Try following
foreach (var car in data.cars)
{
var model = car.model.ToString();
cars = new List<Car>
{
new Car { Model = model }
};
}
Upvotes: -1