linq - How to add children to an object graph in C#, given the parent? -


I have several objects in C # which are almost like this:

  A : {Id: 1, parent: {id: 2, guardian: {id: 3, guardian: zero}}}  

and,

  b : {Id: 4 guardian: {ID: 2 guardian: {id: 3 guardian: null}}}  

I want to combine both and want to reverse it:

combined: {id 3: hair: {id2, hair: {id: 4, hair: empty hair: {id: 1, child: zero}}}

Class looks like this May include:

  public class MyObject {public string ID; Parent MyObject; } Public class combined object {public string id; Public IList & lt; Combined Object & gt; hair; }  

It should be very easy and should be a good declarative way to do this, is not it? I can not figure it out without using very ugly loops.

There may be a better solution, but here's a knife:

  MyObject A = GetA (); MyObject B = GetB (); & Lt; MyObject & gt; AllObjects = GetObjects (A) .Connect (GetObjects (B)) .GroupBy (x = & gt; x.Id) // Duplicate Exit Select (g = & gt; g.First ()). Ollist (); Ice cream & lt; String, string & gt; LookupByParentId = All Objects Where (x => x.Parent! = Null). ToLookup (x => x.Parent.Id, x => x.Id); Dictionary & lt; String, composite object & gt; AllCombinedObjects = allObjects. Select (x = & gt; new composite object () {id = x.Id, child = zero;}) .Onocation (x => x.Id); Forresh (All Combined Objects Coimbiband Object Value.) {Co.Cield = LookupParenintID [Co.ID]. Select (ChildID => All Combined Objects [ChildID]). Ollist (); } Hashaseet & lt; String & gt; Root NodeKeys = New HashSet (All Objects. Where (x => x.Parent == Blank). Select (x => x.Id)); & Lt; CombinedObject & gt; RootNodes = allCombinedObjects.Values. Where (x = & gt; RoutonDirect. Resources (x.Id)) .Oolist ();  

Where GetObjects is defined:

  Public IEnumerable & lt; MyObject & gt; GetObjects (MyObject Source) {MyObject current = source; While (current! = Null) {yield returns current; Current = current Spinach; }}  

Comments