Reputation: 332
I get some informations in a Dataset, and i would like to cast it in a strongly type object. For example my dataset have :
TableName : tab_data
Rows : 1
Columns : Name, FirstName, Address
So i created a class like :
public class Customer
{
public String Name;
public String FirstName;
public String Address;
}
Is there a magic trick to simply cast my dataset to Customer type ? Use LiNQ ?
Thanks,
Upvotes: 2
Views: 4130
Reputation: 1
Here is example of how can you convert a Dataset into Strongly typed object. There are some situations where we get data into dataset through some other source which might not be strongly typed. But Dataset allows us to convert data into strongly typed object.
List<Customer> CustomerList =
(from row in ds.Tables[0].AsEnumerable()
select new Customer
{
Name = row.Field<string>("Name"),
FirstName = row.Field<string>("FirstName"),
Address = row.Field<string>("Address")
}).ToList();
Upvotes: 0
Reputation: 1062512
You can't cast this, but you can translate the data...
The answer is probably different for 1 table than it is for 20; on an individual bases, you should just be able to Select
out the data (or alternatively, just iterate) - this will be the fastest option, but is lots of maintenance if you have lots of tables. In the latter case, some kind of reflection, perhaps like so.
Upvotes: 2
Reputation: 1499790
Is there any reason you haven't created a strongly-typed DataSet to start with? That would probably be the easiest solution.
You can certainly convert each DataTable into (say) a List<Customer>
using the AsEnumerable
extension to DataTable
and a projection which creates a Customer
from a DataRow
if you really need to.
Upvotes: 4