tags:

views:

53

answers:

1

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>

+2  A: 

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.)

Jon Skeet
Oops!!!!!!!! you are Irresistible in brilliancy
can i use this utility for .NET 3.5 (C# 3.0) ?
The code above works in 3.5, yes. If you want to use Zip you can grab in from morelinq.
Jon Skeet