Convert SqlDataReader to linq expression

Viewed 15060

When looking at examples on the internet on how to use SqlDataReader I found things like:

var command = new SqlCommand(  // initialize with query and connection...
var reader = command.ExecuteReader();

while(reader.Read())
{
    var foo = reader["SomeColName"];
    // etc
}

Can I use the following extension method:

public static IEnumerable<IDataReader> ToEnumerable(this IDataReader reader)
{
     while (reader.Read())            
         yield return reader;            
}  

In order to execute queries using linq?

If I use the following extension method will it be bad? If I care about performance should I use the first implementation?

3 Answers

I frequently use this construct:

//(here simplified for the demo purposes)  
internal static List<string> GetList(string SQLiteDB, string Field)
{
    using (SqliteConnection con = new SqliteConnection(SQLiteDB))
    {
        con.Open();
        using (SqliteDataReader DtaReader = new SqliteCommand(@"SELECT " + Field + @" FROM table", con).ExecuteReader())
        {
            return (from IDataRecord r in DtaReader select (string)r[Field]).ToList();
        }
    }
}
Related