Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SqlDataReader to linq expression

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?

like image 668
Tono Nam Avatar asked Dec 04 '22 01:12

Tono Nam


1 Answers

You just need to cast your IEnumerable to IEnumerable<IDataRecord>

var enumerable = reader.Cast<IDataRecord>();
var col = enumerable.Select(record => record .GetOrdinal("SomeColName"));
like image 121
Kalten Avatar answered Dec 24 '22 21:12

Kalten