I would like to create a linq like extension method to get all items from a hierarchical structure like a tree.
This is my extension
public static List<T> GetAllRecursive<T, TU>(this IList<T> list, Func<T, TU> func) where TU : IEnumerable<T> {
var allList = new List<T>();
var toAdd = list.ToList();
while(true) {
allList.AddRange(toAdd);
var childs = toAdd.SelectMany(x => func(x)).ToList();
if(childs.Count == 0) {
return allList;
}
toAdd = childs;
}
}
I call it like this
var allGuidelines = Guidelines.GetAllRecursive(x => (IEnumerable<MachineGuidelineTreeItemViewModel>)x.Children);
How can I improve this method so I don't need to cast every time I use this?
Thanks in advance
BindableCollection<TreeItemViewModel>it means it can contain any descendant ofTreeItemViewModel, not justMachineGuidelineTreeItemViewModel, so it's not safe to cast it toIEnumerable<MachineGuidelineTreeItemViewModel>. You might know it's safe at runtime but compiler sure cannot.