0

How do I convert a dictionary keys' to array in Unity 4.3? (other than manually, of course)

This solution doesn't seem to work, and I'm puzzled about why.

Code:

private Dictionary<int,Client> uid2Client;
public static int[] uidList
{
    get
    {
        return instance.uid2Client.Keys.ToArray();
    }
}

Error:

Assets/sources/ClientServer.cs(144,57): error CS1061: Type `System.Collections.Generic.Dictionary<int,Client>.KeyCollection' does not contain a definition for `ToArray' and no extension method `ToArray' of type `System.Collections.Generic.Dictionary<int,Client>.KeyCollection' could be found (are you missing a using directive or an assembly reference?)

3 Answers 3

7

The ToArray() method is not a standard part of the KeyCollection class. It's an extension method added by Linq.

Add Using System.Linq; to the beginning of your class file.

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

2 Comments

Actually, they cover this in the first comment on the accepted solution to the question you link...
Didn't notice the comment. They say they are ephemeral and should be incorporated into the posts, don't they? ;)
0

You can try manually extracting the keys into an array:

int[] getKeys()
{
    List<int> keys = new List<int>();
    var keycollection = uid2Client.Keys;
    foreach(var key in keycollection)
    {
        keys.Add(key);
    }
    int[] keyArray = keys.ToArray();
    return keyArray;
}

1 Comment

Sure I can do it manually, the whole point of this question is to understand if there is an automatic, possibly one-line, way. Also, to understand why that other method doesn't work.
-1
int[] KeysToArray(){

    int[] array = new List<int>(dictionary.keys).ToArray();

    return array;

}

1 Comment

Why would you want to create a list before converting it to an array? That's just double the work and memory consumption.

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.