[英]Iterating all items in nested list and returning new list of different type
我有這樣的來源清單:
class Foo {
public int ID;
public List<Foo> Children;
}
// Then somewhere else...
Foo root = new Foo(); // The Children is a nested list
然后,我可以訪問一個新類型來進行更改:
class Bar : Foo {
public string Name;
}
我想做的是創建一個新的Bar
,它是上述root
變量的副本,但是在每個項目中都有Name
屬性的值。 在此示例中,它可以是默認值。
我已經試過從root
的Children
LINQ的Select(...)
,但是即使那是正確的路徑,我也無法將語法記下來。
到目前為止,我只在root
列表的第一級子項上起作用。 我需要它來遍及所有級別的兒童。
Bar = new ObservableCollection<Bar>(root.Children.Select(c => new Bar { Name = "Foo" }));
如果深度合理,則可以使用遞歸lambda和LINQ輕松完成:
Func<Foo, Bar> resultSelector = null;
resultSelector = source => new Bar
{
ID = source.ID,
Name = "Foo",
Children = source.Children.Select(resultSelector).ToList<Foo>()
};
Foo result = resultSelector(root);
如果深度太大並導致堆棧溢出,則LINQ不適用,您可以對兩個顯式堆棧使用迭代方法:
var resultStack = new Stack<Bar>();
var childrenStack = new Stack<List<Foo>.Enumerator>();
var result = new Bar { ID = root.ID, Name = "Foo", Children = new List<Foo>() };
var children = root.Children.GetEnumerator();
while (true)
{
while (children.MoveNext())
{
var child = children.Current;
var resultChild = new Bar { ID = child.ID, Name = "Foo", Children = new List<Foo>() };
result.Children.Add(resultChild);
if (child.Children.Count == 0) continue;
resultStack.Push(result);
childrenStack.Push(children);
result = resultChild;
children = child.Children.GetEnumerator();
}
if (resultStack.Count == 0) break;
result = resultStack.Pop();
children = childrenStack.Pop();
}
// Here the result is fully populated
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.