如何最好地使用C#DbDataReader循环一批结果

Bri*_*ney 0 c# dbdatareader

我正在批量执行一些SQL查询,然后批量获取所有结果集.我的代码当前放在一起的方式,第一个结果集被跳过.现在我知道了这一点,我可以简单地在我的循环之外引用另一个声明来获取第一个结果,但是我想知道是否有更优雅的解决方案来解决这个问题.

这里有一些sudo代码:

DbDataReader reader= /*some stuff that returns a batch of results...*/;

while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do things with the data....
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

现在我原本期望NextResult()在你第一次调用它时将你带到第一个结果,这就是Read()似乎做的事情.然而它实际上似乎是在第一次通话时带你到第二个结果.我是否误解了您希望如何使用此方法,或者您是否真的希望执行以下操作:

DbDataReader reader= /*some stuff that returns a batch of results...*/;

//this deals with the row in the the very first result
while (reader.Read())
{
    if (!reader.IsDBNull(0))
    {
        //do things with the data....
    }
}

//this deals with the rest of the rows...
while (reader.NextResult())
{
   while (reader.Read())
   {
       if (!reader.IsDBNull(0))
       {
           //do exact same things with the data....
           //is this not pretty klugey?
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

这让我觉得糟糕的编程风格,但我没有看到它的方法.有谁知道更优雅的解决方案吗?

Guf*_*ffa 9

只需将NextResult放在循环的末尾而不是开头:

do {
   while (reader.Read()) {
      if (!reader.IsDBNull(0)) {
         //do things with the data....
      }
   }
} while (reader.NextResult());
Run Code Online (Sandbox Code Playgroud)