2

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.

2
  • How many values do you have inside a zValuesSet? Did you insert some duplicate values? Because I can't reproduce with few simple values Commented May 20, 2020 at 11:22
  • and what is your question then? Commented May 20, 2020 at 11:31

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

That's what i wanted to use at first but I get an error when writing it, saying this is not defined for SortedSet
which version of framework are you using? I tested here and it´s working with core 2.0
I've tested with .net standard and core and worked fine, I think you're missing a using System.Linq. Moreover, it also worked with CopyTo
Was not using System.Linq, that's much better now thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.