Convert SqlCommand Output to List<MyType>?

て烟熏妆下的殇ゞ 提交于 2019-12-01 10:57:07

You can use LINQ with a DataReader:

var list = reader.Cast<IDataRecord>()
                 .Select(dr => new YourType { Name = dr.GetString(0), ... })
                 .ToList();

The most efficient way is using datareader:

var items = new LinkedList<MyClass>();
using(var connection = GetConnection()) {
    using(var cmd = connection.CreateCommand()){
        cmd.CommandText = "... your SQL statement ...";
        // ... add parameters

        cnn.Open();
        using(var reader = cmd.ExecuteReader()) {
            // accessing values via number index is most efficient

            //gets index of column with name "PrimaryKey"
            var ndxPrimaryKey = reader.GetOrdinal("PrimaryKey");
            var ndxColumn1 = reader.GetOrdinal("Column1");
            var ndxColumn2 = reader.GetOrdinal("Column2");

            while(reader.Read()) {
                var item = new MyClass();

                // returns value of column "PrimaryKey" typed to nullable Guid
                item.PrimaryKey = reader.GetValue(ndxPrimaryKey) as Guid?; 
                item.Column1 = reader.GetValue(ndxColumn1) as string;
                item.Column2 = reader.GetValue(ndxColumn2) as int?;

                items.AddLast(item);
            }
        }
        cnn.Close();
    }
}

return items;
Ardalan Shahgholi

i think you can use Dapper to convert a query to a class.

for more information see my answer in this link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!