Convert SqlCommand Output to List?

2019-02-19 10:02发布

I am using an ADO.NET SqlCommand with a single SqlDbType.Structured parameter to send a table-valued parameter to a sproc. The sproc returns many rows, which I need to get into a strongly-Typed List of . What is the best way to convert the result set (whether DataTable from a DataAdapter or DataReader bits) into List?

Thanks.

3条回答
SAY GOODBYE
2楼-- · 2019-02-19 10:11

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;
查看更多
ら.Afraid
3楼-- · 2019-02-19 10:21

You can use LINQ with a DataReader:

var list = reader.Cast<IDataRecord>()
                 .Select(dr => new YourType { Name = dr.GetString(0), ... })
                 .ToList();
查看更多
趁早两清
4楼-- · 2019-02-19 10:31

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

for more information see my answer in this link

查看更多
登录 后发表回答