【问题标题】:Several unusual errors when attempting to convert a string[] to a Dictionary<short, string>尝试将 string[] 转换为 Dictionary<short, string> 时出现几个异常错误
【发布时间】:2010-12-05 13:45:39
【问题描述】:

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

        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>'

我对此感到非常困惑,无法弄清楚。有人可以帮忙吗?

【问题讨论】:

    标签: c# .net collections lambda ienumerable


    【解决方案1】:

    你注意到ToDictionary&lt;TSource,TKey&gt;中Source和Key的顺序了吗?

    你可以试试:

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

    【讨论】:

    • 完全没有注意到,非常感谢!不过我现在有点累了……
    • 这就是为什么最好把它留给编译器:splitProgram.ToDictionary(value => i++);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多