C# 遞迴 無限階層

C# 遞迴

結構

//資料結構
public class OrgModel
{
    public List<OrgClass> Organization { get; set; }// 組織
    public class OrgClass
    {
        public string OrgId { get; set; }        //組織編號
        public string OrgName { get; set; }      //組織名稱
        public string ElderId { get; set; }      //上層組織編號
        public List<OrgClass> OrgL { get; set; }  //組織
    }
}

 

遞迴無限階層

/// <summary>
/// 遞迴無限階層
/// </summary>
/// <param name="Org">原始資料</param>
/// <param name="StartId">開始查詢的ID</param>
/// <param name="OrgKey">本次ID=下次上級ID</param>
/// <returns></returns>

public List<OrgModel.OrgClass> RecursivelyOrg(List<OrgModel.OrgClass> Org ,string StartId,string OrgKey)
{
    var returnData = new List<OrgModel.OrgClass>();
    if (Org != null)
    {
        var Org2 = new List<OrgModel.OrgClass>();
        if (StartId != null)
        {
            Org2 = Org.Where(o => o.OrgId == StartId).ToList();  //第一次
        }
        else
        {
            Org2 = Org.Where(o => o.ElderId == OrgKey).ToList(); //第2~N次
        }
        foreach (var p in Org2)
        {
            var dc = new OrgModel.OrgClass
            {
                OrgId = p.OrgId ,
                OrgName = p.OrgName ,
                ElderId = p.ElderId ,
                OrgL = RecursivelyOrg(Org ,null ,p.OrgId) , //遞迴
            };
            returnData.Add(dc);
        }
    }
    return returnData;
}

 

預設資料 執行

//預設資料
var returnData = new OrgModel();
var DataList = new List<OrgModel.OrgClass> {
    new OrgModel.OrgClass { OrgId = "1" ,OrgName = "A" ,ElderId = null },
    new OrgModel.OrgClass { OrgId = "2" ,OrgName = "B" ,ElderId = "1" },
    new OrgModel.OrgClass { OrgId = "3" ,OrgName = "C" ,ElderId = "1" },
    new OrgModel.OrgClass { OrgId = "4" ,OrgName = "D" ,ElderId = "2" },
    new OrgModel.OrgClass { OrgId = "5" ,OrgName = "E" ,ElderId = "4" },
    new OrgModel.OrgClass { OrgId = "6" ,OrgName = "F" ,ElderId = "3" },
};

//執行
returnData.Organization = RecursivelyOrg(DataList ,"1" ,"");

結果圖

我只是一棵樹