尝试将string []转换为Dictionary <short,string =“”> </short,>时出现几个异常错误

时间:2009-10-10 09:47:44

标签: c# .net collections lambda ienumerable

我有以下代码在新行上拆分字符串并将其转换为字典以供进一步处理:

        string[] splitProgram = program.Split(Environment.NewLine.ToCharArray());
        short i = 0;
        Dictionary<short, string> programDictionary = splitProgram.ToDictionary<short, string>((value) => i++);

奇怪的是我在第三行遇到以下错误:

Error 1 Instance argument: cannot convert from 'string[]' to 'System.Collections.Generic.IEnumerable<short>'
Error 2 'string[]' does not contain a definition for 'ToDictionary' and the best extension method overload 'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>)' has some invalid arguments
Error 3 Argument '2': cannot convert from 'lambda expression' to 'System.Func<short,string>'

我对这一点感到非常难过,无法弄明白。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

您是否注意到ToDictionary<TSource,TKey>中的来源和密钥的顺序?

你可以尝试:

//untested
... = splitProgram.ToDictionary<string, short>((value) => i++);