我正在从存储过程中接收数据到列表中,然后我想使用父级和子级ID将此列表转换为层次结构。我所做的是:
型号:
public class AllAccounts
{
[Column("account_id")]
public Guid AccountID { get; set; }
[Column("parent_id")]
public Guid ParentID { get; set; }
[Column("theaccount_name")]
public string AccountName { get; set; }
[Column("paren_tname")]
public string ParentName { get; set; }
[Column("thedescription")]
public string Description { get; set; }
[Column("glcode")]
public string code { get; set; }
[Column("is_bankaccount")]
public bool BankAccountStatus { get; set; }
[Column("bank_acountnumber")]
public string AccountNumber { get; set; }
[Column("thecurrency")]
public string AccountCurrency { get; set; }
[Column("referenceaccount")]
public Nullable<int> AccountReference { get; set; }
[Column("thestatus")]
public string AccountStatus { get; set; }
public List<AllAccounts> Children = new List<AllAccounts>();
}
此处的帐户ID为子ID,其父代为父ID。
从存储过程接收数据并找到其根父ID的函数。
public async Task<object> GenerateArrangedCOAList(string businessID, string coaid)
{
//calling stored procedure and sending Chart Of Account and fetching data
Guid guidBusinessID = new Guid(businessID);
Guid guidAccountid = coaid != null ? new Guid(coaid) : new Guid();
var list = await Task.Run(() => webFUDBContext.allAccounts.FromSqlRaw("select * from exportcoa('"+guidBusinessID+"', '" + guidAccountid + "')").ToList());
var allAccounts = new List<AllAccounts>();
for (int a = 0; a < list.Count; a++)
{
var parentAccountId=list[a].ParentID;
var parentAccountname = list[a].ParentName;
for(int b = 0; b < list.Count; b++)
{
AllAccounts allAccounts1 = new AllAccounts();
if (list[b].AccountID == parentAccountId && list[b].AccountName == parentAccountname)
{
allAccounts1.ParentName = parentAccountname;
allAccounts1.ParentID = parentAccountId;
allAccounts1.AccountID = list[b].AccountID;
var childr = FillRecursive(list, parentAccountId);
allAccounts1.Children.Add(childr);
allAccounts.Add(allAccounts1);
list.RemoveAt(b);
}
}
}
return allAccounts;
}
创建父级和子级ID的递归函数:
private dynamic FillRecursive(List<AllAccounts> flatObjects, Guid accountID)
{
List<AllAccounts> recursiveObjects = new List<AllAccounts>();
foreach (var item in flatObjects.Where(x => x.ParentID.Equals(accountID)))
{
recursiveObjects.Add(new AllAccounts
{
AccountID = item.AccountID ,
Children = FillRecursive(flatObjects, item.AccountID)
});
}
return recursiveObjects;
}
enter code here