Reputation: 1014
I need to create an array from data I get form my API. The data needs to be in the object Entry
which I get from the MicroCharts Library.
error is: Index was outside the bounds of the array.
on the 2nd line.
the most this is one of my tries:
var entries = new[]{ new Entry(2) { } };
entries[2]=( new Entry(3) { });
for (int i = 0; i < _CoinHistory.Count(); i++)
{
var price_float = float.Parse(_CoinHistory[0].price_btc);
entries[i] = new Entry(price_float) { };
}
the hardcoded part that works is this:
var entries = new[]
{
new Entry(200)
{
},
new Entry(400)
{
},
new Entry(-100)
{
}
};
edit:Both the answer from zaitsman as the answer from PiotrWolkowski work. just like the linq way.
Upvotes: 1
Views: 274
Reputation: 8782
The error means you have exceeded the size of the array.
In C# once array is created it maintains it's size. You determine the size either by initializing the array with required amount of items, like in your example below:
var entries = new[]
{
new Entry(200)
{
},
new Entry(400)
{
},
new Entry(-100)
{
}
};
Or by providing the number of arguments as a parameter
var entries = new Entry[3]
Both will create an array of the size of 3, but the second one will be empty.
In your code in the first line you created an array of size 1 and then tried to assign a value to the third place in the array - which didn't exist.
If you want a dynamically resized collection use a List<Entry>
instead and then, once your processing is completed turn it into an array with ToArray()
call.
You can also initialize an array of the size of your results:
var entries = new Entry[_CoinHistory.Count()]
Upvotes: 1
Reputation: 9499
Why not use Linq?
var entries = _CoinHistory.Select(x => new Entry(x.price_btc)).ToArray()
Upvotes: 2