I have an object that stores hierarchical data. I have successfully been able to create the structure I need from a flat structure, but this required me to use List<>
which isn't immutable (I want to use IReadOnlyList
).
Now I can't really get my head around how I would create immutable lists based on these children lists. Can anyone guide me in the right direction?
The class looks like this:
public class ItemOrFolder
{
public string Id { get; }
public string Name { get; }
public List<ItemOrFolder> Children { get; set; } // Need to create immutable versions of these recursively
private ItemOrFolder(string id, string name)
{
Id = id;
Name = name;
}
public static ItemOrFolder Create(string id, string name)
{
return new ItemOrFolder(id, name);
}
}
If Children
is null
, then it's an item, otherwise it's a folder, containing zero or more ItemOrFolder
.