Merge multiple Lists into one List with LINQ

前端 未结 8 1782
南方客
南方客 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:34

    You can use Aggregate with Zip to zip an arbitrary number of IEnumerables in one go.

    Here's how you might do that with your example:

    var colorLists = new List[] { red, green, blue };
    var rgbCount = red.Count;
    var emptyTriples =
        Enumerable.Repeat>>(() => new List(), rgbCount)
        .Select(makeList => makeList());
    
    var rgbTriples = colorLists.Aggregate(
        emptyTriples,
        (partialTriples, channelValues) =>
            partialTriples.Zip(
                channelValues,
                (partialTriple, channelValue) =>
                {
                    partialTriple.Add(channelValue);
                    return partialTriple;
                }));
    
    var rgbObjects = rgbTriples.Select(
        triple => new RGB(triple[0], triple[1], triple[2]));
    

    Generally, relying on Zip as the underlying combiner avoids problems with varying input lengths.

提交回复
热议问题