Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select data into List<T> instead of DataTable?

Tags:

c#

c#-4.0

This is how currently I'm selecting data from database:

public DataTable GetData()
{
    DataTable table = new DataTable("Table");
    using (SqlConnection connection = new SqlConnection("Connection string"))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = System.Data.CommandType.Text;
        command.CommandText = "query string";

        connection.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        adapter.Fill(table);
    }
    return table;
}

But it return DataTable and I want to select List instead of DataTable. Like this:

public List<MyClass> GetData()
{
    DataTable table = new DataTable("Table");
    using (SqlConnection connection = new SqlConnection("Connection string"))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = System.Data.CommandType.Text;
        command.CommandText = "query string";

        connection.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        adapter.Fill(table);
    }
    ...
    return [List of MyClass];
}

How can I do this?

Thanks!

like image 479
WaterDance Avatar asked May 08 '12 20:05

WaterDance


People also ask

How do you select rows in a DataTable?

You can also click anywhere in the table, and then press CTRL+A to select the table data in the entire table, or you can click the top-left most cell in the table, and then press CTRL+SHIFT+END.

How can I change the DataType of a column in DataTable?

Once a DataTable has been filled, you can't change the type of a column. Your best option in this scenario is to add an Int32 column to the DataTable before filling it: dataTable = new DataTable("Contact"); dataColumn = new DataColumn("Id"); dataColumn. DataType = typeof(Int32); dataTable.


2 Answers

If you want to use the DataRowCollection to populate a list of custom objects, you could use LINQ and an object initializer:

var lst = table.AsEnumerable().Select(r =>
    new MyObject
    {
        FirstProperty = r.Field<int>("FirstProperty"),
        OtherProperty = r.Field<string>("OtherProperty")
    }).ToList(); 
like image 165
James Johnson Avatar answered Sep 19 '22 19:09

James Johnson


I'd recommend you to use dapper-dot-net, if you do not want to dig into LINQ to SQL or Entity Framework. Fumbling around yourself with IDataReader to materialise your result isn't worth the effort in most cases.

like image 40
Matthias Meid Avatar answered Sep 22 '22 19:09

Matthias Meid