2016-04-21 101 views
1

有一個類型A的列表,每個列表都包含一個B類型的列表,獲取所有類型B的列表的最佳方式是什麼?每個列表都包含它們所屬的類型A的列表?在LINQ中反轉嵌套集合

擁有一個像列表如下:

var parents = new List<Parent> { 
    { 
     new Parent { 
      ID = 1, 
      Childs = new List<Child> { 
       { 
        new Child { 
         ID = 1 
        } 
       }, 
       { 
        new Child { 
         ID = 2 
        } 
       }, 
       { 
        new Child { 
         ID = 3 
        } 
       } 
      } 
     }      
    }, 
    { 
     new Parent { 
      ID = 2, 
      Childs = new List<Child> { 
       { 
        new Child { 
         ID = 3 
        } 
       }, 
       { 
        new Child { 
         ID = 4 
        } 
       }, 
       { 
        new Child { 
         ID = 5 
        } 
       } 
      } 
     }      
    } 
}; 

我想查詢此獲得以下結果:

[ 
    { 
    Child = 1, 
    InParent = [1] 
    }, 
    { 
    Child = 2, 
    InParent = [1] 
    }, 
    { 
    Child = 3, 
    InParent = [1, 2] 
    }, 
    { 
    Child = 4, 
    InParent = [2] 
    }, 
    { 
    Child = 5, 
    InParent = [2] 
    }, 
] 

編輯:我想首先拼合孩子的一種方法使用SelectMany & Distinct,但不知道如何將其再次鏈接到父級:

var foo = 
    from childId in parents.SelectMany(x => x.Childs).Select(x => x.ID).Distinct() 
    select 
     new 
     { 
      childId = childId, 
      inParent = // Missing Part 
     }; 
+2

在問一個問題之前,你有嘗試過什麼嗎?你有什麼問題? – wudzik

+0

當然,我試圖用SelectMany/Distinct扁平孩子,它返回所有涉及孩子的清單,但沒有連接到他們所屬的父母。當然,我可以循環遍歷它,我的問題是如何在LINQ查詢中實現這一點。 –

回答

4

你必須使用SelectMany先展平,然後,再由孩子-ID使用GroupBy分組和String.Join到Concat的每個父ID:

var childParents = parents 
    .SelectMany(p => p.Childs.Select(c => new {Parent = p, Child = c})) 
    .GroupBy(x => x.Child.ID) 
    .Select(g => new 
    { 
     Child = g.Key, 
     InParent = String.Join(", ", g.Select(x => x.Parent.ID)) 
    }); 

結果:

enter image description here

如果你不想InParent屬性是一個字符串,但是List<int>(或數組)使用這個:

..... 
InParent = g.Select(x => x.Parent.ID).ToList() // or ToArray() 
0

您可以分割你的大問題分成兩個簡單的問題:

  1. 每個父/子對創建一個匿名的對象,包含的母公司,以及對孩子的引用。你可以使用一個簡單的LINQ查詢和兩個from子句。

  2. 將這些對象分組到您需要的表示中。 group by條款是你的朋友在這裏。

-1

我想你應該嘗試改變你的數據模型,如果你正在尋找存儲樹狀結構,在那種情況下你應該總是使用與自定義對象單鏈表&嵌套參考類似相應的父/子你存儲在數據庫中的方式。

這是一種理想的方式來處理這樣的數據結構,否則您將最終在許多嵌套查詢。