EDIT: Now that we have a little more context, it looks like you actually have XML for a start. However, we still do not know what processing you are doing on the elements. XSLT may be the right approach, but using LINQ to XML and its Descendants
method will be different:
var doc = XDocument.Load(stream); var descendants = doc.Descendants("Folder");
This may be even simpler than the XSLT approach. For example, if you want to convert it to List<string>
by taking an attribute from each element:
var doc = XDocument.Load(stream); var names = doc.Descendants("Folder") .Select(x => (strong) x.Attribute("name")) .ToList();
One drawback is that it will still load the entire XML file into memory as XElement
objects (etc.). It is possible that the XSLT version can handle this in a streaming manner with more efficient use of memory. Dimitre, without a doubt, provides more information, if that matters.
There is nothing in LINQ to smooth out several levels of a hierarchy without performing a recursion. SelectMany
performs one level of anti-aliasing, but you will need to reorganize to reduce your multi-level hierarchy to a single list.
Now, if you use LINQ to XML, this is very convenient - you can simply use the Descendants
method:
var allFolders = root.Descendants("Folder");
To write something like this for your domain class, you will need to write more code. If you can provide more information about what you have (XML or domain classes), we can help you more.
EDIT: Well, it looks like XML is a red herring. But finding all the descendants is quite simple. You can do this with iterator blocks, but it is rather unpleasantly inefficient rather quickly. Here is another simple alternative:
public IList<Folder> SelfAndDescendants() { List<Folder> ret = new List<Folder>(); AddSelfAndDescendants(ret); return ret; } private void AddSelfAndDescendants(IList<Folder> list) { list.Add(this); foreach (var child in children) { AddSelfAndDescendants(list); } }
You can customize the exact algorithm based on the order in which you want the children back.