Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取CollectionBase项目的列表?_C#_Linq_Collectionbase - Fatal编程技术网

C# 如何获取CollectionBase项目的列表?

C# 如何获取CollectionBase项目的列表?,c#,linq,collectionbase,C#,Linq,Collectionbase,在C#中,如果我有一个T类型的CollectionBase,并且CollectionBase中的每个项都可以有一个T类型相同的子CollectionBase,那么我如何在不使用递归函数的情况下获得所有T类型对象的列表 LINQ有这样的功能吗 提前谢谢。韦斯·戴尔写了一个很好的主题,祝你愉快 对于您的案例,我认为您需要一个迭代器,可能类似于这样: public static IEnumerable<T> Flatten<T>(this IEnumerable<T>

在C#中,如果我有一个T类型的CollectionBase,并且CollectionBase中的每个项都可以有一个T类型相同的子CollectionBase,那么我如何在不使用递归函数的情况下获得所有T类型对象的列表

LINQ有这样的功能吗


提前谢谢。

韦斯·戴尔写了一个很好的主题,祝你愉快

对于您的案例,我认为您需要一个迭代器,可能类似于这样:

public static IEnumerable<T> Flatten<T>(this IEnumerable<T> e, Func<T,IEnumerable<T>> f) 
{
   return e.SelectMany(c => f(c).Flatten(f)).Concat(e);
}
公共静态IEnumerable展平(此IEnumerable e,Func f)
{
返回e.SelectMany(c=>f(c).展平(f)).Concat(e);
}
这是我的答案

编辑:我只记得你也可以编辑树

public static IEnumerable<T> Traverse<T>(T item, Func<T, IEnumerable<T>> childSelector)
{
    var stack = new Stack<T>();
    stack.Push(item);
    while (stack.Any())
    {
        var next = stack.Pop();
        yield return next;
        foreach (var child in childSelector(next))
        stack.Push(child);
    }
}
公共静态IEnumerable遍历(T项,Func子项选择器)
{
var stack=新堆栈();
堆栈。推送(项目);
while(stack.Any())
{
var next=stack.Pop();
其次是收益率;
foreach(childSelector中的var child(下一个))
栈.推(子);
}
}

子项是否可以包含子项等?你为什么不想使用递归?看这个。你能给我们展示一些CollectionBase的代码吗?我想这是你要找的。