Code challenge time! And by code challenge, I mean, "Do my work for me so I don't have to think/Google".
We have a parent object, called Parent, and each one has a collection of child objects, called AllegedChild. Ignore potential cycles for this exercise. The database has a single table with fields: ParentID, ParentName, ChildID, ChildName. The data is such:
1, Coding Hillbilly, 1, Brandi-Lynn
1, Coding Hillbilly, 2, Sammy-Jo
1, Coding Hillbilly, 3, Sammy-Jo Jr.
1, Coding Hillbilly, 4, Sammy-Jo Sr.
2, Donald Belcham, 5, Justice Gray
2, Donald Belcham, 5, Dave Laribee
2, Donald Belcham, 5, Scott
We will retrieve this list into a collection of ParentChildDto objects with properties that mirror the database. From this list, we'd like to create a new list of Parent objects each with an appropriate list of AllegedChild objects.
The challenge, given a List<ParentChildDto>, what is a clean and efficient way of creating a List<Parent>? The current implementation looks something like this:
private List<Parent> GitEm( IEnumerable<ParentChildDto> flatList )
rFrom = from p in flatList
ParentChildDto prev = null;
var to = new List<Parent>( );
foreach( var dto in rFrom )
if(prev == null || prev.ParentId != dto.ParentId)
prev = new Parent
Id = dto.ParentId,
FullName = dto.Name
prev.AllegedChildren = new List<AllegedChild>();
if(dto.ChildId != null)
Id = dto.ChildId,
FullName = dto.Name
While this works, it looks a little too old-school what with the funky indentation and the use of a "previous" placeholder. But try as I might, I can't think of another solution that would be cleaner or more maintainable. There's a chance I may be too "close" to the problem though.
Honorary Hillbilly Status awaits the person who provides an answer deemed worthy of the domain upon which this example is based. Answers must assume a cordial tone and work within the context outlined. Ones that do not (hint: These will be the answers that take the form "Why are you doing XXXX in the first place?" or one of its variations) will be summarily dismissed.
Kyle the Advancefully Grateful