Populating object properties from DataSet using LINQ
Here is my current relationship
DataRelation relation = new DataRelation("EventCategoryRelation", eventsTable.Columns["event_id"], eventCategoriesTable.Columns["event_id"]);
ds.Tables.Add(eventsTable);
ds.Tables.Add(eventCategoriesTable);
ds.Relations.Add(relation);
Here is a quick look through the tables
EventsTable
event_id | event_description
1 || "First Event"
EventCategoriesTable
event_category_id || event_id || category_id
1 || 1 || 1
2 || 1 || 2
Relationship is many-to-many (one event is to many categories)
Here is how I populate my DTO's using a foreach loop
foreach (DataRow row in eventsTable.Rows)
{
Event events = new Events();
events.Description = row["event_description"].ToString();
DataRow[] aDr = row.GetChildRows("EventCategoryRelation");
foreach (DataRow dr in aDr)
{
Categories category = new Categories();
categ开发者_JAVA技巧ory.CategoryID = Int64.Parse(dr["category_id"].ToString());
events.CategoryList.Add(category);
}
}
I have more fields on my actual code. I want to replace the foreach loop with a LINQ query. Is that possible?
So you are basically transforming each DataRow into a Categories object and adding them to the event? You can achieve this sort of thing by using a Linq Select, (this is termed a projection).
To create a list of Categories ...
DataRow[] aDr = row.GetChildRows("EventCategoryRelation");
var categoryList = aDr.Select(row => new Categories()
{
category.CategoryID = Int64.Parse(dr["category_id"].ToString());
});
// add them to your event
events.CategoryList.AddRange(categoryList);
// or ...
events.CategoryList = categoryList.ToList();
The last step, where you add your categories to the event depends on the type of your CategoryList, whether it has an AddRange method, or whether you can set it to a new collection or list of categories.
You can then combine the outer for-each as follows:
var eventsList = eventsTable.AsEnumerable().Select(eventRow => new Events()
{
Description = eventRow["event_description"].ToString(),
CategoryList = eventRow.GetChildRows("EventCategoryRelation")
.Select(row => new Categories()
{
category.CategoryID = Int64.Parse(row["category_id"].ToString());
})
.ToList()
}
Note this uses the following extension methods on DataTable:
http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable.aspx
精彩评论