我有一个通用列表List<String, String> ListName

我正在尝试将列表的值插入字典Dictionary<String, int>

我看了看地方,但只发现将字典的元素添加到列表中。虽然我的要求是相反的。我尝试使用toDictionary,但是它对我没有用。不知道出了什么问题。

是否有人尝试将值从列表插入字典?

最佳答案

我认为您的意思是List<string[]>,因为我之前从未见过通用的List<T,WhoAmI>

如果使用List<string[]>,则可以使用ToDictionary功能

List<string[]> ListName = new List<string[]>();
ListName.Add(new[] { "Stack", "1" });
ListName.Add(new[] { "Overflow", "2" });

// Select the first string([0]) as the key, and parse the 2nd([1]) as int
Dictionary<string,int> result = ListName.ToDictionary(key => key[0], value => int.Parse(value[1]));


如果您在列表中使用某种自定义对象,也可以使用相同的方法

List<MyObject<string, string>> ListName = new List<MyObject<string, string>>();
Dictionary<string, int> result = ListName.ToDictionary(key => key.String1, value => int.Parse(value.String2));


public class MyObject<T, U>
{
    public MyObject(T string1, U string2)
    {
        String1 = string1;
        String2 = string2;
    }

    public T String1 { get; set; }
    public U String2 { get; set; }
}


注意:您应该在int.Parse周围添加错误检查,或者如果可能不是数字,请使用Int.TryParse

关于c# - 将通用列表元素添加到字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14888541/

10-12 07:37
查看更多