I have a treeview with the following structure:
var myTree = myRepository.GetTree();
Where the object Folder is structured in this way:
public class Folder
{
public string Name { get; set; }
public List<Folder> Folders { get; set; }
public Folder Parent { get; set; }
}
Assuming that a repository is returning to me something like this structure:
MyFolder
-MyChild01
-MyChild02
-MySubChild01
-MyChild03
-MySubChild02
I need to recursively read all the items in the tree and if the item has the name containing '02' I have to remove the item from the tree. So the final result should be:
MyFolder
-MyChild01
-MyChild03
I would like to see how to do this using a recursive LINQ with anonymous delegate or with a recursive function.
There's a number of approaches you could take to do this.
The easiest thing to do would be to take a functional approach and rebuild the tree recursively excluding the folders that match your pattern.
static Folder Filtered(Folder root, Func<Folder, bool> predicate)
{
return new Folder
{
Name = root.Name,
Parent = root.Parent,
Folders = root.Folders
.Where(predicate)
.Select(subFolder => Filtered(subFolder, predicate))
.ToList(),
};
}
Folder myTree = ...;
var filtered = Filtered(myTree, f => f.Name.Contains("02"));
If for whatever reason you would rather not make new instances of your Folders but would rather modify the existing instances, some adjustments would have to be made but still equally simple.
static Folder Filtered(Folder root, Func<Folder, bool> predicate)
{
// make use of the RemoveAll() method for lists
root.Folders.RemoveAll(subFolder => !predicate(subFolder));
foreach (var subFolder in root.Folders)
{
Filtered(subFolder, predicate);
}
return root;
}
static void Main(string[] args)
{
var root = new Folder()
{
Name = "MyFolder",
Folders = new List<Folder>(){
new Folder() {Name="MyChild01", Folders = new List<Folder>()},
new Folder() {Name="MyChild02", Folders = new List<Folder>(){
new Folder() { Name="MySubChild01", Folders = new List<Folder>()}}
},
new Folder() {Name="MyChild03", Folders = new List<Folder>(){
new Folder() { Name="MySubChild02", Folders = new List<Folder>()}}
},
}
};
var filtered = applyFilter(root, f=>!f.Name.EndsWith("02"));
}
static Folder applyFilter( Folder root, Predicate<Folder> filter )
{
var result = new Folder() { Name = root.Name, Parent = root.Parent };
result.Folders = (from child in root.Folders
where filter(child)
select applyFilter(child, filter)).ToList();
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With