【问题标题】:Read SQL Table into Dictionary<string, List<string[]>>将 SQL 表读入 Dictionary<string, List<string[]>>
【发布时间】:2012-10-23 20:15:45
【问题描述】:

我有一个如下所示的 SQL 表:

AAA, Amanda, Anthony
AAA, Anna, Andrew
BBB, Boris, Benji
BBB, Blondie, Bobby

我正在尝试使用 SQL 数据阅读器来读取数据,然后将结果插入到 Dictionary&lt;string, List&lt;string[]&gt;&gt;

预期结果是:

[Key]
   "AAA"
[Value]
   "Amanda", "Anthony"
   "Anna", "Andrew"
[Key]
   "BBB"
[Value]
   "Boris", "Benji"
   "Blondie", "Bobby"

请帮忙:

using (SqlConnection cnn = new SqlConnection("connection"))
{
   using (SqlCommand cmd = new SqlCommand("command", cnn))
   {
      using (SqlDataReader rdr = cmd.ExecuteReader())
      {
         while (rdr.Read())
            {
               ... ?
            }
      {
   {
}

【问题讨论】:

  • 你需要问一个具体的问题。
  • 我会认真考虑您是否真的想将多个值放在一列中,就像您正在做的那样。通常会有一个地方你会后悔这样做......
  • @RBarryYoung:你什么意思?我正在寻求帮助,将 SQL 表中的记录插入到字典中。为什么是 -1?
  • @AbeMiessler:“通常情况下,你会后悔这样做......”_例如,什么时候?
  • 当您想将您创建的隐含父子关系视为实际父子关系时。带有示例的答案太大而无法包含在评论中。这实际上可能是一个很好的 SO 问题......

标签: c# .net vb.net list data-dictionary


【解决方案1】:

我认为这很简单。通读您的数据表,并为每一行检查 [key] 是否存在于您的字典中。如果没有,请使用包含您的 [value] 的新列表添加它;否则,将 [value] 添加到 List 的 [key] 位置。

如果你对数据表进行排序,你可以使用经典的控制中断技术来加速这个过程——对于每个新的 [key],开始累积一个 List,直到 [key] 发生变化,然后将 [key] 和 List 添加到你的字典。

【讨论】:

    【解决方案2】:
    while (rdr.Read())
    {
        if (dictionary.ContainsKey((string)rdr["column1"]){
            dictionary[(string)rdr["column1"]].Value.Add(new string[]{(string)rdr["column2"], (string)rdr["column3"]});
        } else {
            dictionary.Add((string)rdr["column1"]), new List<string>());
            dictionary[(string)rdr["column1"]].Value.Add(new string[]{(string)rdr["column2"], (string)rdr["column3"]});
        }
    }
    

    这应该可行。

    【讨论】:

      【解决方案3】:

      类似的东西:

       var dict = new Dictionary<string, List<string[]>>();
       while (rdr.Read())
       {
           // TODO: extract field1, field2, field3
           if(dict.ContainsKey(field1))
           {
               // Add the values to the existing list
               dict[field1].Add(new string [] {field2 , field3});
           }
           else
           {
               //Create a new list and set the initial value
               dict[field1] = new List<string[]> { new string[] { field2 , field3 } };
           }
       }
      

      【讨论】:

        【解决方案4】:

        可能是这样的吗?

        myDict.Add(rdr["key"].ToString(), rdr["value"].ToString().Split(",").ToList());
        

        未经测试,但它应该能让你朝着正确的方向前进......

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-27
          • 2015-07-02
          相关资源
          最近更新 更多