Can I create an anonymous type collection from a DataReader?

后端 未结 4 551
没有蜡笔的小新
没有蜡笔的小新 2021-02-09 06:22

I have this code:

var query = \"SELECT * FROM Cats\";

var conn = new SqlConnection(sqlConnectionString);

conn.Open();

var cmd = new SqlCommand(query);
var rea         


        
4条回答
  •  时光说笑
    2021-02-09 07:06

    You can create helper generic method and let compiler infer type parameter:

    private IEnumerable Select(DbDataReader reader, Func 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 Select(this DbDataReader reader, Func 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) });
    

提交回复
热议问题