Copying values from sortedset to array

Viewed 249

I'm currently working on a project where i use a sorted set and I then need to put them in an array to iterate over it using index. I came to a strange problem where the CopyTo method wasn't working properly and I'd like to know if there is a real reason for it. My code was:

SortedSet<float> zValuesSet = new SortedSet<float>();

//Insert some values in the set

float[] zValues = new float[zValuesSet.Count];
zValuesSet.CopyTo(zValues);

Using this, i came with an error telling me the I was assigning more values in zValues than its capacity, even if I used the Set.Count to get the capacity. To solve my problem, I used:

List<float> zValuesList = new List<float>(zValuesSet);
float[] zValues = zValuesList.ToArray();

However, this may lead to a cost that (I guess ?) could be avoided using the first method. So I'm wondering about why this happends ?

EDIT : That was my bad, I'm using multiple occurencies of this kind of set and I misspelled it... So the copy to is working well.

1 Answers

You can directly convert to an array this way:

 SortedSet<float> zValuesSet = new SortedSet<float> { 1, 2, 3 };

 float[] zValues = zValuesSet.ToArray();

Here working: https://ideone.com/xphVAJ

Related