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?
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.
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? 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.
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With