递归列表压扁 [英] Recursive List Flattening

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

问题描述

我大概可以写我自己,但具体的办法,我想完成它扔我。我想写类似其他的通用扩展方法引入.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构造做,那是相当简单的 - 虽然递归使用iterator块的效率比较低。是这样的:

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天全站免登陆