user215675
user215675

Reputation: 5181

C# Supplying Custom Keys

How to supply custom key as dictionary keys?

When i execute the code: I receive

    int[] Keys={5567,51522,35533};
    string[] values={"one","two","three"};
    var dic = values.ToDictionary(key=>Keys.ToArray());
    foreach (KeyValuePair<int, string> kv in dic)
    {
        Console.WriteLine("Key={0},value={1}", kv.Key, kv.Value);
    }

Error :can not convery KeyValuePair<int[],string> to KeyValuePair<int,string>

Upvotes: 0

Views: 253

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500893

Currently, you're using the whole array of keys for each element in the dictionary. You want something like:

var dic = Enumerable.Range(0, keys.Length)
                    .ToDictionary(i => keys[i],
                                  i => values[i]);

(Or use the Zip method from .NET 4.0 to zip the two collections together, then form a dictionary from that.)

Upvotes: 2

Related Questions