1

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.

2 Answers 2

2

Why not use Linq?

var entries = _CoinHistory.Select(x => new Entry(x.price_btc)).ToArray()
Sign up to request clarification or add additional context in comments.

3 Comments

how would you do this for an IEnumerable?
an array is IEnumerable? so you can return an array where that is expected as well as pass an array where IEnumerable is expected
yup, fault on my side. fairly new to this.
1

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()]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.