我有以下數據結構,我想將它轉換爲基於RelationId的層次結構。這是根據RelationId排序的。基於數字序列將對象轉換爲層次結構
id = 2具有relationId = 2並且以下兩行具有realtionId = 0。這代表了ID = 3和Id = 4是Id的子= 2
Id Name RelationId SortOrder
1 A 1 1
2 B 2 2
3 C 0 3
4 D 0 4
5 E 3 5
6 F 0 6
7 G 0 7
8 H 4 8
最終結果將是象以下
Id = 1
|
Id = 2
|___ Id = 3 , Id = 4
Id = 5
|___ Id= 6 , Id=7
Id = 8
期望的結果是如下(爲簡單起見表示它作爲列表) 。這將是在C#中List<Something>
Result =
[
{ Id = 1, Name = A, Children = Null },
{ Id = 2, Name = B, Children = [{ Id = 3, Name = C }, {Id = 4, Name = D }] },
{ Id = 5, Name = E, Children = [{ Id = 6, Name = F }, {Id = 7, Name = G }] },
{ Id = 8, Name = H}
]
我不成功的嘗試是如下
var finalResult = new List<sampleDataClass>();
var sampleData = GetMeSampleData();
var count = sampleData.Count();
foreach (var item in sampleData)
{
var alreadyExist = finalResult.Any(x => x.Id == item.Id);
var newObject = new sampleDataClass();
if (!alreadyExist && item.RelationId!= 0)
{
newObject = item;
}
for (int i = item.SortOrder; i < count; i++)
{
if (sampleData[i].RelationId== 0)
{
newObject.Children.Add(sampleData[i]);
}
}
finalResult.Add(newObject);
}
你爲什麼不使'RelationId'點在父的'Id' ?只需使用0或-1或其他值來表示它是頂級父級? – juharr
這是一個排序數組,relationId = 1是頂級 – InTheWorldOfCodingApplications
添加了sortOrder字段以及 – InTheWorldOfCodingApplications