将通用列表的元素添加到字典中

时间:2013-02-15 05:03:00

标签: c# dictionary generic-list

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

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

我看了几个地方,但发现只添加字典列表。虽然我的要求是相反的。我尝试使用toDictionary,但它对我没用。不确定出了什么问题。

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

3 个答案:

答案 0 :(得分:3)

我认为你的意思是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

答案 1 :(得分:1)

您可以这样使用:

List<KeyValuePair<String, String>> ListName = new List<KeyValuePair<String, String>>();
Dictionary<String, Int32> dict = new Dictionary<String, Int32>();
ListName.ForEach(e=> dict.Add(e.key, Int32.Parse(e.Value)));

答案 2 :(得分:0)

我不确定整数的来源究竟在哪里,但这样的事情应该有效:

Dictionary<string, int> dict = new Dictionary<string, int>();
list.ForEach(x => dict.Add(x, theInteger));
相关问题