2014-04-03 29 views
0

我從存儲過程中獲取查詢數據,並且需要將其分組爲3個通用列表。我不知道如何解決這個問題。將C#組數據庫查詢結果嵌入到嵌套的泛型列表中

以下是從數據的查詢結果如下總結:

Child | Parent | GrandChildren 
a2  | a1  | a30 
a2  | a1  | a31 
a2  | a1  | a32 

b2  | b1  | b30 
b2  | b1  | b31 

c2  | c1  | c30 

d2  | d1  | d30 
d2  | d1  | d31 
d3  | d1  | d32 
d3  | d1  | d33 

這裏是我想對數據進行分組。

public class Parent 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public List<Child> Children { get; set; } 
} 

public class Child 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public List<GrandChild> GrandChildren { get; set; } 
} 

public class GrandChild 
{ 
    // numerous properties. 
} 

這是我試過的,但沒有運氣。

var data = Repository.GetData(); 
var groupedData = from d in data 
        where d.Parent > 0 
        group d by d.Parent into ParentGroup 
        select parentGroup.ToList(); 

// Result: Grouped list of "Parent", not with grouped "Child" and grouped "GrandChildren" as per desired structure above. 
+1

你也得組孫子們。這不會自動發生。我會嘗試先創建孫子組,然後將孩子分組在一起,然後閱讀每個父母。當你完成後,這將是一個相當毛茸茸的表情。我會擔心查詢運行時間。 –

+0

@Tony感謝您的快速回復。我不確定你能否給我一個如何組合孫子女的開端。 –

回答

0

您將不得不將子孫也分組。像這樣的事情:

var data = Repository.GetData(); 

// Group the Grandchildren first 
var grandkids = from d in data 
       where d.Child > 0 
       group d by d.Child into GrandChildGroup 
       select new Grandchild { 
        // Assign grand child properties here 
       }; 

// Group the Children 
var children = from d in data 
       where d.Parent > 0 
       group d by d.Parent into ChildGroup 
       select new Child { 
        // Assign child properties here 
        Grandchildren = (from gc in grandkids 
            where gc.Parent = d.Child 
            select gc).ToList() 
       }; 

// Now group the parents 
var groupedData = from p in data 
        select new Parent { 
         // Assign parent properties here 
         Children = (from kid in children 
            where kid.Parent = p.Parent 
            select kid).ToList() 
        }.ToList(); 
+0

非常感謝。我會試試這個。 –