开发者

C# Supplying Custom Keys

How to supply custom key as dictionary keys?

When i execute the code: I receiv开发者_C百科e

    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>


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜