我们有一个班级列表
public class DummyClass
{
public string Text { get; set; }
public int LevelNo { get; set; }
public List<DummyClass> Children { get; set; }
}
我们希望将此列表添加到带有类的另一个列表中。
public class FragmentLevel
{
public int currentLevelNo { get; set; }
public int ParentLevelNo { get; set; }
public string Text { get; set; }
}
我们需要像
这样的结果var list = new List<FragmentLevel>
{
new FragmentLevel{ id = 1, text = "Root" },
new FragmentLevel{ id = 2, parent= 1, text = "Node-1.1" },
new FragmentLevel{ id = 3, parent= 2, text = "Node-1.1.1" }
};
为了获得结果,我们正在做
for (int i = 0; i < DummyClassList.Count; i++)
{
list.Add(new FragmentLevel
{
currentLevelNo = DummyClassList[i].LevelNo,
Text = DummyClassList[i].Text,
});
do
{
for (int j = 0; j < DummyClassList[i].Children.Count; j++)
{
list1.Add(new FragmentLevel
{
LevelNo = DummyClassList[i].Children[j].LevelNo,
Text = DummyClassList[i].Children[j].Text,
});
}
} while (DummyClassList[i].Children[i].Children != null);
}
但这会给出错误的结果。我们如何才能得到结果?
答案 0 :(得分:0)
尝试这种递归填充片段的方式,
private static void FillFragments(List<DummyClass> DummyClassList, List<FragmentLevel> list)
{
for (int i = 0; i < DummyClassList.Count; i++)
{
list.Add(new FragmentLevel
{
currentLevelNo = DummyClassList[i].LevelNo,
Text = DummyClassList[i].Text,
});
if (DummyClassList[i].Children != null && DummyClassList[i].Children.Count > 0)
{
FillFragments(DummyClassList[i].Children, list);
}
}
}
,主要方法看起来像这样
static void Main(string[] args)
{
var DummyClassList = new List<DummyClass>
{
new DummyClass
{
Children = new List<DummyClass>
{
new DummyClass{
Children = null,
LevelNo=2,
Text = "two"
}
},
LevelNo = 1,
Text = "one"
}
};
var list = new List<FragmentLevel>();
FillFragments(DummyClassList, list);
}