ネストされたコレクションがあります。ネストされたコレクションにループ解析する前に、親コレクションの各要素をループしたいです。
私がこれまでに試したことは、
Private void Loop( PreviewObject po )
{
Console.Writeline(po.Name) ;
foreach (PreviewObject child in po.Childrens)
Loop( child);
}
PreviewObject クラス
public class PreviewObject
{
private string _name;
public string Name { get { return _name; } set { _name = value; } }
private List<PreviewObject> _childrens = new List<PreviewObject>();
public List<PreviewObject> Childrens
{
get { return _childrens; }
set { _childrens = value; }
}
}
問題は、ループが次のようになることです
X をコレクションと仮定し、X には要素 X があり、ネストされたコレクションを意味します。
X の最初の要素は A 、X の 2 番目の要素は B、X の最初の要素のコレクションの最初の要素は C
これをコードとしてループすると、次の結果が得られます。
AC X
私が手に入れたいのは、
A
B C
A と B はどちらも親コレクションの要素なので、最初にすべての親要素をループしたいのですが、親要素のコレクション内の要素をループします。
誰でもこれを達成するのを手伝ってもらえますか?
次のコードを試しましたが、同じ結果が得られました
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections ;
namespace Breadth_first_traversal
{
class Program
{
public static void Main(string[] args)
{
list a = new list();
a.name = "A";
list b = new list();
b.name = "B";
list c = new list();
c.name = "C";
list d = new list();
d.name = "d";
list parent = new list();
parent.name = "Parent";
parent.Childrens.Add(a);
parent.Childrens.Add(b);
a.Childrens.Add(c);
b.Childrens.Add(d);
Loop(a);
Console.ReadKey();
}
private static void Loop(list po)
{
Queue<list> queue = new Queue<list>();
queue.Enqueue(po);
while (queue.Count != 0)
{
list next = queue.Dequeue();
foreach (list obj in next.Childrens)
queue.Enqueue(obj);
// Replace with the actual processing you need to do on the item
Console.WriteLine(next.name);
}
}
public class list
{
public string _name;
public string name { get { return _name; } set { _name = value; } }
private List<list> childrens = new List<list>();
public List<list> Childrens { get { return childrens ; } set {childrens = value ; } }
}
}
}
上記のコードで得た結果は
交流
しかし、私が取得しなければならないのは
あいうえお
最初に親コレクションのすべての要素をコンソールに書き込み、次に親のコレクション要素のコレクションをコンソールに書き込むため
誰かが素敵なコード例で答えることができますか?