【问题标题】:c# - Dictionary<string, List<string>> to DataGridc# - Dictionary<string, List<string>> 到 DataGrid
【发布时间】:2017-09-25 10:43:10
【问题描述】:

我有以下问题:

我有一个填充的列表字典,每个电梯都有一个指定的已知长度,并且只包含字符串,示例元素是:

d1[key] = [ "Text1", "Text2", "Text3", "Text4", "0", "0", "0", "0", "0" ]

数据网格将具有与键对应的预先声明的列,以及 8 个列表元素中的每一个,总共 9 列。

我写这个是为了尝试填充 DataGrid,有没有更有效的方法,基本上将每一行都写入数据网格。字典可能有超过 1k 个键。

public static void DictionaryToDataGrid(Dictionary<string, List<string>> inputdict1)
    {
        Dictionary<string, List<string>> d1 = inputdict1;

        foreach (KeyValuePair<string, List<string>> item in d1)
        {
            DatagridForm.grid.Rows.Add(item.Key, item.Value[0], item.Value[1], item.Value[2]);
        }
    }

有没有更快、更有效的方法来做到这一点?谢谢。

【问题讨论】:

  • 我觉得你用的方法效率很高。
  • 跳过将参数复制到d1 并直接使用inputdict1
  • 会更适合Code Review

标签: c# dictionary datagridview datagrid


【解决方案1】:

更短的版本是:

    foreach (KeyValuePair<string, List<string>> item in inputdict1)
        DatagridForm.grid.Rows.Add(item.Key, item.Value[0], item.Value[1], item.Value[2]);

这也更有效率,因为您没有创建新变量 d1,而是引用 inputdict1的内容> 给它(感谢启示录)。

希望这会有所帮助。

【讨论】:

  • 它只是将引用分配给一个新变量。没有任何内容被复制到 d1
猜你喜欢
  • 1970-01-01
  • 2018-08-04
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-28
相关资源
最近更新 更多