我想创建一个linq像扩展方法来从层次结构像树一样获取所有项目。使用嵌套的泛型没有很多的代码
这是我的分机
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;
}
}
我这样称呼它
var allGuidelines = Guidelines.GetAllRecursive(x => (IEnumerable<MachineGuidelineTreeItemViewModel>)x.Children);
我怎样才能改善这个梅索德所以我不需要投,每次我用这个?
在此先感谢
孩子的返回类型是什么? –
,你为什么需要将它转换为IEnumerable呢?是不是x.Children IEnumerable <>已经?它是一个更通用的类型,例如,IEnumerable
孩子是一个BindableCollection –
horotab