Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dataset to List<T>using linq

Tags:

linq

dataset

I have a DataSet and I want to convert the DataSet into List<T>

T - type object

How convert my DataSet? It has 10 columns, with all 10 properties my object has and it's returning over 15000 rows. I want to return that dataset into List<obj> and loop it how do I do that?

like image 730
bharat Avatar asked May 26 '10 21:05

bharat


People also ask

How do you load data into DataSet so that it can be queried using LINQ?

Data sources that implement the IEnumerable<T> generic interface can be queried through LINQ. Calling AsEnumerable on a DataTable returns an object which implements the generic IEnumerable<T> interface, which serves as the data source for LINQ to DataSet queries.

Can we use LINQ on DataSet?

LINQ to DataSet makes it easier and faster to query over data cached in a DataSet object. Specifically, LINQ to DataSet simplifies querying by enabling developers to write queries from the programming language itself, instead of by using a separate query language.

Can we use LINQ to query against a DataTable?

Can we use linq to query against a DataTable? Explanation: We cannot use query against the DataTable's Rows collection, since DataRowCollection doesn't implement IEnumerable<T>. We need to use the AsEnumerable() extension for DataTable.


2 Answers

This is pretty much the same as the other answers, but introduces strongly-typed columns.

var myData = ds.Tables[0].AsEnumerable().Select(r => new {
    column1 = r.Field<string>("column1"),
    column2 = r.Field<int>("column2"), 
    column3 = r.Field<decimal?>("column3")
});
var list = myData.ToList(); // For if you really need a List and not IEnumerable
like image 86
Greg Avatar answered Oct 07 '22 13:10

Greg


I think this should do it.

var output = yourDataSet.Tables[0].Rows.Cast<DataRow>().Select(r => new
{
    Column1 = r["Column1"].ToString(),
    Column2 = r["Column2"].ToString(),
    Column3 = r["Column3"].ToString(),
    Column4 = r["Column4"].ToString(),
    Column5 = r["Column5"].ToString(),
    Column6 = r["Column6"].ToString(),
    Column7 = r["Column7"].ToString(),
    Column8 = r["Column8"].ToString(),
    Column9 = r["Column9"].ToString(),
    Column10 = r["Column10"].ToString()
}).ToList();
like image 37
Kelsey Avatar answered Oct 07 '22 12:10

Kelsey