Merge multiple lists with variable length “popping” elements from each

后端 未结 7 836
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 08:30

I\'d like to sort multiple lists (variable number of them) into single list, but keeping the specific order. For example:

List A: { 1,2,3,4,5 }
List B: { 6,7         


        
7条回答
  •  不知归路
    2020-12-21 08:51

    I'd go with:

    static void Main(string[] args)
    {
        var a = new List() { 1, 2, 3, 4, 5 };
        var b = new List() { 6, 7, 8 };
        var c = new List() { 9, 10, 11, 12 };
    
        var abc = XYZ(new[] { a, b, c }).ToList();
    }
    
    static IEnumerable XYZ(IEnumerable> lists)
    {
        if (lists == null)
            throw new ArgumentNullException();
        var finished = false;
        for (int index = 0; !finished; index++)
        {
            finished = true;
            foreach (var list in lists)
                if (list.Count > index) // list != null (prior checking for count)
                {
                    finished = false;
                    yield return list[index];
                }
        }
    }
    

    I had to use use IList to have indexer and Count. It doesn't creates anything (no enumerators, no lists, etc.), purely yield return.

提交回复
热议问题