c# - How to convert datatable record into child custom Class -
i have 2 classes namely:
public class parent { public int id { get; set; } public int { get; set; } public int b { get; set; } } public class child : parent { public int c { get; set; } public int d { get; set; } }
and have 2 datatables following records
datatable (parent table) id b 1 2 4 2 3 6 3 8 7 4 5 9 datatable ii (child table) parentid c d 2 4 10 4 9 7
if want convert parent datatable parent objects user following code:
ilist<parent> items = dt.asenumerable().select(row => new parent { id = row.field<int>("id"), = row.field<int>("a"), b = row.field<int>("b"), }).tolist();
obviously parent objects id of 2 , 4 has created child objects have no idea how that.
please me on this. in advance.
you wrote:
obviously parent objects id of 2 , 4 has created child objects
that not obvious. according layout, table ii have 2 rows same parentid, in example mean 2 people living together, while property , b address , telephone number while property c , d might mean birthday , favourite sport: 2 people living same address , telephone number , different birthday , different favourite sport.
if wanted express in database there 1 child parent id 2 , 1 child parent id 4, database wouldn't match first normal database form , different table layout prevent 2 people living better.
having said that, guess want following:
create list children table ii , add parents don't have child in table ii. properties , b children should taken table id equals parentid.
- create dictionary parents i
- create sequence children ii, use dictionary find values properties , b
- take parents don't have child in ii
- concat children , last parent list
.
var parentdictionary = asenumerable().todictionary(p => p.id); ienumerable<parent> children = ii.asenumerable() .where( c => parentdictionary.keys.contains(c.parentid)) .select(c => new child() { = parentdictionary[c.id].a, b = parentdictionary[c.id].b, c = c.c, d = c.d }) .cast<parent>(); ienumerable<parent> parentswithoutchildren = i.asenumerable() .where(p => !ii.asenumerable().contains(p.id)); ienumerable<parent> requestedpersons = parentswithoutchildren .concat(children);
Comments
Post a Comment