Can I create an anonymous type collection from a DataReader?

后端 未结 4 562
没有蜡笔的小新
没有蜡笔的小新 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:01

    It's possible, although not particularly neat. We'll need to create a new method that will allow us to create an empty sequence that allows for type inference off of a dummy value for starters:

    public static IEnumerable Empty(T dummyValue)
    {
        return Enumerable.Empty();
    }
    

    This lets us create a list of an anonymous type:

    var list = Empty(new
    {
        CatName = "",
        CatDOB = DateTime.Today,
        CatStatus = 0
    }).ToList();
    

    (The item here isn't used.)

    Now we can add our anonymous types to this list:

    var cmd = new SqlCommand(query);
    var reader = cmd.ExecuteReader();
    
    while (reader.Read())
    {
        list.Add(new
        {
            CatName = reader.GetString(0),
            CatDOB = reader.GetDateTime(1),
            CatStatus = reader.GetInt32(2),
        });
    }
    

    Of course, using a named type would likely be easier, so I would suggest using one unless there is a real compelling reason not to do so. That is especially true if you plan to use the list outside of the scope it's created in.

提交回复
热议问题