Can I create an anonymous type collection from a DataReader?
c#, datareader
Solution
You can create helper generic method and let compiler infer type parameter:
private IEnumerable<T> Select<T>(DbDataReader reader, Func<DbDataReader, T> selector)
{
while(reader.Read())
{
yield return selector(reader);
}
}
usage:
var items = SelectFromReader(reader, r => new { CatName = r.GetString(0), CarDOB = r.GetDateTime(1), CatStatus = r.GetInt32(2) });
You can even make the method an extension method on `DbDataReader`:
public static IEnumerable<T> Select<T>(this DbDataReader reader, Func<DbDataReader, T> selector)
{
while (reader.Read())
{
yield return selector(reader);
}
}
and use it like that:
var items = reader.Select(r => new { CatName = r.GetString(0), CarDOB = r.GetDateTime(1), CatStatus = r.GetInt32(2) });
Problem
I have this code: ``` var query = "SELECT * FROM Cats"; var conn = new SqlConnection(sqlConnectionString); conn.Open(); var cmd = new SqlCommand(query); var reader = cmd.ExecuteReader(); while (reader.Read()) { var CatName = reader.GetString(0); var CatDOB = reader.GetDateTime(1); var CatStatus = reader.GetInt32(2); } ``` I'd like to pull the rows out into an anonymous type collection, which I'd normally do using LINQ to iterate, but I an not sure if it's possible due to the way you have to call `.Read()` each time to get the next row. Is there a way to do this?