简体   繁体   中英

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.

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 }

The solution below is very straight forward. As it turns out, it is also nearly twice as fast as the solution proposed by dtb.

private static IEnumerable<T> Interleave<T>(this IEnumerable<IEnumerable<T>> source )
{
    var queues = source.Select(x => new Queue<T>(x)).ToList();
    while (queues.Any(x => x.Any())) {
        foreach (var queue in queues.Where(x => x.Any())) {
            yield return queue.Dequeue();
        }
    }
}

Here's my attempt, based on dtb's answer . It avoids the external SelectMany and internal ToArray calls.

public static IEnumerable<T> Interleave<T>(this IEnumerable<IEnumerable<T>> source)
{
    var enumerators = source.Select(e => e.GetEnumerator()).ToArray();
    try
    {
        bool itemsRemaining;
        do
        {
            itemsRemaining = false;
            foreach (var item in 
                     enumerators.Where(e => e.MoveNext()).Select(e => e.Current))
            {
                yield return item;
                itemsRemaining = true;
            }
        }
        while (itemsRemaining);
    }
    finally
    {
        Array.ForEach(enumerators, e => e.Dispose());
    }
}
  • Disposed all enumerators, even when exceptions are thrown
  • Evaluates the outer sequence eagerly, but uses lazy evaluation for the inner sequences.

public static IEnumerable<T> Interleave<T>(IEnumerable<IEnumerable<T>> sequences)
{
    var enumerators = new List<IEnumerator<T>>();
    try
    {
        // using foreach here ensures that `enumerators` contains all already obtained enumerators, in case of an expection is thrown here.
        // this ensures proper disposing in the end
        foreach(var enumerable in sequences)
        {
            enumerators.Add(enumerable.GetEnumerator());
        }

        var queue = new Queue<IEnumerator<T>>(enumerators); 
        while (queue.Any())
        {
            var enumerator = queue.Dequeue();
            if (enumerator.MoveNext())
            {
                queue.Enqueue(enumerator);
                yield return enumerator.Current;
            }
        }
    }
    finally
    {
        foreach(var enumerator in enumerators)
        {
            enumerator.Dispose();
        }
    }
}

Though its not as elegant as "dtb"'s answer, but it also works and its a single liner :)

Enumerable.Range(0, items.Max(x => x.Count()))
                      .ToList()
                      .ForEach(x =>
                                   {
                                            items
                                            .Where(lstChosen => lstChosen.Count()-1 >= x)
                                            .Select(lstElm => lstElm.ElementAt(x))
                                            .ToList().ForEach(z => Console.WriteLine(z));
                                   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM