【问题标题】:C# Populate dictionary directly from SqlDataReaderC# 直接从 SqlDataReader 填充字典
【发布时间】:2016-10-21 15:52:49
【问题描述】:

在我一直在研究的一个程序中,将数据放入已创建的字典中需要三个步骤:

  1. 执行 SQL 命令
  2. 将这些结果拉入DataTable,然后
  3. DataTable拉入Dictionary

代码:

var myDr = myLookup.ExecuteReader();
dt.Load(myDr);
customerLookup = dt.AsEnumerable()
    .ToDictionary(key => key.Field<string>("code"),
    value => value.Field<string>("customerText"));

我的问题是,是否可以“去掉中间人”,可以这么说,将SqlDataReater 中的数据直接拉到字典中?还是有必要先将其拉入DataTable?如果我想做的事情是可能的,有人可以发布代码让我尝试吗?

非常感谢!

【问题讨论】:

  • 试试这个:myDr.Read(); while(myDr != null) { customerLookup.Add(myDr["code"], myDr["customerText"]);myDr.Read(); }

标签: c# sql-server dictionary sqldatareader


【解决方案1】:

您可以只遍历阅读器返回的行:

var customerLookup = new Dictionary<string, string>();
using (var reader = myLookup.ExecuteReader())
{
    while (reader.Read())
    {
        customerLookup[(string)reader["code"]] = (string)reader["customerText"];
    }
}

您应该知道,如果有任何重复的代码,后续代码值将覆盖字典中以前的代码值。如果您希望在这种情况下抛出异常,您可以改用customerLookup.Add()

【讨论】:

    【解决方案2】:

    是的,这是可能的。你应该使用SqlDataReader.Read 方法。

    【讨论】:

      【解决方案3】:

      不仅可以,而且绝对应该。正如您所展示的那样,该代码表明完全不了解 .NET 的工作原理。

      我建议的一些代码对于手头的问题可能被认为是“矫枉过正”,但它确实展示了一些最佳实践。

      Dictionary<string, string> customerLookup = new Dictionary<string, string>();
      using (var reader = myLookup.ExecuteReader())
      {
          int ordinalCode = reader.GetOrdinal("code");
          int ordinalCustomerText = reader.GetOrdinal("customerText");
          while (reader.Read())
          {
              //this code assumes the values returned by the reader cannot be null
              customerLookup.Add(reader.GetString(ordinalCode), reader.GetString(ordinalCustomerText))
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-25
        • 1970-01-01
        • 1970-01-01
        • 2016-11-01
        相关资源
        最近更新 更多