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

后端 未结 7 789
被撕碎了的回忆
被撕碎了的回忆 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 09:08

    Shortest and probably slowest solution

    int[] A = { 1, 2, 3, 4, 5 };
    int[] B = { 6, 7, 8 };
    int[] C = { 9, 10, 11, 12 };
    
    
    var arrs = new[] { A, B, C };
    var merged = Enumerable.Range(0, arrs.Max(a => a.Length))
        .Select(x => arrs.Where(a=>a.Length>x).Select(a=>a[x]))
        .SelectMany(x=>x)
        .ToArray();
    

    upd.

    Another way to solve - I just refactored @Sinatr answer.

    static IEnumerable<T> XYZ<T>(IEnumerable<IList<T>> lists)
    {
        if (lists == null)  
            throw new ArgumentNullException();
        var index = 0;
    
        while (lists.Any(l => l.Count > index))
        {
            foreach (var list in lists)     
                if (list.Count > index)         
                    yield return list[index];       
            index++;
        }
    }
    
    0 讨论(0)
提交回复
热议问题