2016-09-30 98 views
4

我有如下的表結構。在父子層次結構中查找深度級別

Id |ParentId| Name 
--- |--------|------- 
1 |NULL |A 
2 |1  |B 
3 |2  |C 
4 |3  |D 

A是B的母公司,B是C的父母和C是D.

的父母我想計算如何可能父母每條記錄有哪些? 例如B指的是A,C指的是B,而D指的是C.

在這種情況下,A的深度級別爲0,B爲1,C爲2,D爲3,有。

我可以使用遞歸函數來做到這一點,每次查詢記錄是否有父項。我想以高效的方式使用linq查詢來實現這一點。

回答

0

我認爲最好的方法來實現這個沒有超過計算,多個請求或臨時SQL表是一次選擇所有表在Dictionary並在C#端計算父計數。

如果它是你可以接受它可以使用這個功能,除了類,以防止過度的計算來完成:

public class ParentInfo 
{ 
    public int? ParentId { get; } 

    public int? ParentCount { get; set; } 

    public ParentInfo(int? parentId) 
    { 
     ParentId = parentId; 
    } 
} 

private static int GetParentCount(int id, IDictionary<int, ParentInfo> conections) 
{ 
    if (!conections.ContainsKey(id)) 
     throw new InvalidDataException($"Id = {id} not found in connections"); 
    var info = conections[id]; 
    if (info.ParentCount.HasValue) return info.ParentCount.Value; 

    var result = 0; 
    if (info.ParentId.HasValue) result += 1 + GetParentCount(info.ParentId.Value, conections); 
    info.ParentCount = result; 
    return result; 
} 

然後你就可以得到使用此代碼的結果是:

var conections = table.ToDictionary(r => r.Id, r => new ParentInfo(r.ParentId)); 
var result = conections.Select(c => new 
{ 
    Id = c.Key, 
    ParentCount = GetParentCount(c.Key, conections) 
}).ToArray(); 
相關問題