递归列表展平 [英] Recursive List Flattening

查看:31
本文介绍了递归列表展平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能自己写这个,但我试图完成它的具体方式让我失望.我正在尝试编写一个类似于 .NET 3.5 中引入的其他方法的通用扩展方法,它将采用 IEnumerables 的嵌套 IEnumerable(等等)并将其展平为一个 IEnumerable.有人有什么想法吗?

I could probably write this myself, but the specific way I'm trying to accomplish it is throwing me off. I'm trying to write a generic extension method similar to the others introduced in .NET 3.5 that will take a nested IEnumerable of IEnumerables (and so on) and flatten it into one IEnumerable. Anyone have any ideas?

具体来说,我在扩展方法本身的语法方面遇到了问题,因此我可以使用展平算法.

Specifically, I'm having trouble with the syntax of the extension method itself so that I can work on a flattening algorithm.

推荐答案

嗯...我不确定正是你想要什么,但这里有一个一级"选项:>

Hmm... I'm not sure exactly what you want here, but here's a "one level" option:

public static IEnumerable<TElement> Flatten<TElement,TSequence> (this IEnumerable<TSequence> sequences)
    where TSequence : IEnumerable<TElement> 
{
    foreach (TSequence sequence in sequences)
    {
        foreach(TElement element in sequence)
        {
            yield return element;
        }
    }
}

如果这不是您想要的,您能否提供您想要的签名?如果您不需要通用表单,而只想做 LINQ to XML 构造函数所做的事情,那相当简单——尽管迭代器块的递归使用效率相对较低.类似的东西:

If that's not what you want, could you provide the signature of what you do want? If you don't need a generic form, and you just want to do the kind of thing that LINQ to XML constructors do, that's reasonably simple - although the recursive use of iterator blocks is relatively inefficient. Something like:

static IEnumerable Flatten(params object[] objects)
{
    // Can't easily get varargs behaviour with IEnumerable
    return Flatten((IEnumerable) objects);
}

static IEnumerable Flatten(IEnumerable enumerable)
{
    foreach (object element in enumerable)
    {
        IEnumerable candidate = element as IEnumerable;
        if (candidate != null)
        {
            foreach (object nested in candidate)
            {
                yield return nested;
            }
        }
        else
        {
            yield return element;
        }
    }
}

请注意,这会将字符串视为字符序列 - 您可能希望将特殊情况的字符串作为单个元素而不是将它们展平,具体取决于您的用例.

Note that that will treat a string as a sequence of chars, however - you may want to special-case strings to be individual elements instead of flattening them, depending on your use case.

这有帮助吗?

这篇关于递归列表展平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆