How to get a DataRow out the current row of a DataReader?

后端 未结 2 898
走了就别回头了
走了就别回头了 2021-02-18 13:12

Ok, I would like to extract a DataRow out a DataReader. I have been looking around for quite some time and it doesn\'t look like there is a simple way

2条回答
  •  故里飘歌
    2021-02-18 13:31

    You're probably asking because you have DataReader code that looks something like this:

    static void ViaDataReader(IDataReader rdr)
    {
        while (rdr.Read())
            Console.WriteLine("{0,-27} {1,-46} {2,-25} {3}", rdr[0], rdr[1], rdr[2], rdr[3]);
    }
    
    /// ...
    
    ViaDataReader(DbProviderFactories.GetFactoryClasses().CreateDataReader());
    

    But as Tim pointed out, if you know in advance that you're going to want the DataRow at each iteration, you should use DataTable instead, and then just iterate on its Rows property (following output is identical to above):

    static void ViaDataTable(IDataReader rdr)
    {
        var table = new DataTable();
        table.Load(rdr);
        foreach (DataRow row in table.Rows)
            Console.WriteLine("{0,-27} {1,-46} {2,-25} {3}", row[0], row[1], row[2], row[3]);
    }
    
    /// ...
    
    ViaDataTable(DbProviderFactories.GetFactoryClasses().CreateDataReader());
    

    If you absolutely must continue using the DataReader for some reason, I suppose you could add a loop index integer to that first example, and then grab each row from the (fully-pre-loaded DataTable) on each iteration. But since the DataTable is richer all-around, there's really no reason not to abandon the DataReader after doing the DataTable.Load().

提交回复
热议问题