Recursive List Flattening

后端 未结 13 1358
既然无缘
既然无缘 2020-11-27 04:25

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 oth

13条回答
  •  青春惊慌失措
    2020-11-27 05:10

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

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

    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.

    Does that help?

提交回复
热议问题