Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

c# - Interleaving multiple (more than 2) irregular lists using LINQ

Say I have the following data

IEnumerable<IEnumerable<int>> items = new IEnumerable<int>[] { 
    new int[] { 1, 2, 3, 4 },
    new int[] { 5, 6 },
    new int[] { 7, 8, 9 }
};

What would be the easiest way to return a flat list with the items interleaved so I'd get the result:

1, 5, 7, 2, 6, 8, 3, 9, 4

Note: The number of inner lists is not known at runtime.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you're describing is essentially a Transpose Method where overhanging items are included and the result is flattened. Here's my attempt:

static IEnumerable<IEnumerable<T>> TransposeOverhanging<T>(
    this IEnumerable<IEnumerable<T>> source)
{
    var enumerators = source.Select(e => e.GetEnumerator()).ToArray();
    try
    {
        T[] g;
        do
        {
            yield return g = enumerators
                .Where(e => e.MoveNext()).Select(e => e.Current).ToArray();
        }
        while (g.Any());
    }
    finally
    {
        Array.ForEach(enumerators, e => e.Dispose());
    }
}

Example:

var result = items.TransposeOverhanging().SelectMany(g => g).ToList();
// result == { 1, 5, 7, 2, 6, 8, 3, 9, 4 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...