0

我们有一个班级名单

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);
                    }

但这会给出错误的结果。我们怎样才能得到结果?

4

1 回答 1

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);

    }
于 2013-05-12T12:29:39.610 回答