Jul 26, 2012

[How to] Convert Dictionary.Keys (or Values) to Array

For example, there's a dictionary like this,


using System.Collections.Generic;


Dictionary<string, int> dict = new Dictionary<string, int>();


Now we want to retrieve all keys,


var keys = dict.Keys;


That is. However, the keys is another collection type an we want to convert it to array.
There was an old way -- CopyTo.


string[] keyArray = new string[dict.Count];
dict.Keys.CopyTo(keyArray, 0);


If you have looking for better solution, and you're using C# 3.0 (and above).
Congratulation! According the MSDN library, there's a directly way -- ToArray



However, when I tried to use it, I found that there's NO ToArray method for the Keys!
Why? After a bit time fighting to my brain, I noticed that it is a extend method of Enumerator.


So, the better solution in C# 3.0 (and above) is,


using System.Collections.Generic;
using System.Linq;


Dictionary<string, int> dict = new Dictionary<string, int>();


string[] keys = dict.Keys.ToArray();
int[] values = dict.Values.ToArray();


That's all, just don't forget the Linq!

5 comments:

  1. Hi,
    what about converting the dictionary into two dimensional array?
    psaudo: object[,] array = dict.(keys+values).toArray();

    ??

    ReplyDelete
  2. Hello Elad,
    I have no idea that how to convert a dictionary to a 2D array directly.
    ToArray() method can not convert your key/value array type to object array, either.
    It means, you need specified a correct array type.
    Any type CAN convert to object , but any array CANNOT convert to object array.

    In my opinion, this conversion do not make sense (according some SE principle)
    You should find other way to solve your problem but not just convert it to array.

    Please tell me how do you want to use your dictionary, may I can give you some suggestion :)

    ReplyDelete
  3. Hi Jordan,
    What I'm trying to do is to write values into a 2D range of an excel spreadsheet.
    I have this open excel worksheet reference (a com object) and I have retrieved the range I needed:
    Range stepsRange = worksheetRange.get_Range("D1", "E14");

    Now, I have this dictionary of 14 pairs of strings which I have to covect to a 2D array:
    object[,] array = dict.(keys+values).toArray();
    So I will be able to use one of the two:
    stepsRange.Value = array;
    or
    stepsRange.GetType().InvokeMember("Value", System.Reflection.BindingFlags.SetProperty, null, test, array);

    The type of the array is not important.
    I've asked a question about this subject in stackoverflow, with no answer so far:
    http://stackoverflow.com/questions/17062599/how-to-set-values-to-a-two-dimensional-excel-range

    Thanks,

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete