Merge multiple Lists into one List with LINQ

前端 未结 8 1799
南方客
南方客 2020-11-28 12:50

Is there a slick way to merge multiple Lists into a single List using LINQ to effectively replicate this?

public class RGB
{
    public int Red { get; set; }         


        
8条回答
  •  被撕碎了的回忆
    2020-11-28 13:29

    You're essentially trying to zip up three collections. If only the LINQ Zip() method supported zipping up more than two simultaneously. But alas, it only supports only two at a time. But we can make it work:

    var reds = new List { 0x00, 0x03, 0x06, 0x08, 0x09 };
    var greens = new List { 0x00, 0x05, 0x06, 0x07, 0x0a };
    var blues = new List { 0x00, 0x02, 0x03, 0x05, 0x09 };
    
    var colors =
        reds.Zip(greens.Zip(blues, Tuple.Create),
            (red, tuple) => new RGB(red, tuple.Item1, tuple.Item2)
        )
        .ToList();
    

    Of course it's not terribly painful to write up an extension method to do three (or more).

    public static IEnumerable Zip(
        this IEnumerable first,
        IEnumerable second,
        IEnumerable third,
        Func resultSelector)
    {
        using (var enum1 = first.GetEnumerator())
        using (var enum2 = second.GetEnumerator())
        using (var enum3 = third.GetEnumerator())
        {
            while (enum1.MoveNext() && enum2.MoveNext() && enum3.MoveNext())
            {
                yield return resultSelector(
                    enum1.Current,
                    enum2.Current,
                    enum3.Current);
            }
        }
    }
    

    This makes things a lot more nicer:

    var colors =
        reds.Zip(greens, blues,
            (red, green, blue) => new RGB(red, green, blue)
        )
        .ToList();
    

提交回复
热议问题