【问题标题】:Adding Elements of generic list to dictionary将通用列表的元素添加到字典
【发布时间】:2013-01-31 01:32:47
【问题描述】:

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

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

我查看了一些地方,但只发现将字典元素添加到列表中。而我的要求正好相反。我尝试使用 toDictionary,但它对我不起作用。不知道出了什么问题。

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

【问题讨论】:

  • 请出示一些代码。
  • List 接受两个类型参数? int 来自哪里?
  • 列表是通用的,读取一个包含三个字段的文件,其中一个是int。所以这里的尝试是使用字符串列和 int 列作为键和值。
  • BCL 通用列表定义为List<T>,而不是List<T,U>。因此,您无法使用 BCL 创建List<string,string>。我们看不到您如何存储文件中的三个字段。请显示一些代码。
  • 显示一些你正在尝试的代码。

标签: c# dictionary generic-list


【解决方案1】:

我假设您的意思是 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,如果它可能不是数字的话。

【讨论】:

  • 我的代码很像 sa_ddam213 提到的 List> ListName = new List>(); Dictionary 结果 = ListName.ToDictionary(key => key.String1, value => int.Parse(value.String2));公共类 MyObject { public MyObject(T string1, U string2, int v) { String1 = string1;字符串 2 = 字符串 2; } 公共 T 字符串 1 { 获取;放; } 公共 U 字符串 2 { 获取;放; } }
【解决方案2】:

你可以这样使用:

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

【讨论】:

    【解决方案3】:

    我不确定整数的确切来源,但应该可以这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2011-03-22
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多