我認爲最好的方法來實現這個沒有超過計算,多個請求或臨時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();