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

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

    For your problem I create static method, which can merge any collections as you want:

    public static class CollectionsHandling
    {
        /// 
        /// Merge collections to one by index
        /// 
        /// Type of collection elements
        /// Merging Collections
        /// New collection {firsts items, second items...}
        public static IEnumerable Merge(params IEnumerable[] collections)
        {
            // Max length of sent collections
            var maxLength = 0;
    
            // Enumerators of all collections
            var enumerators = new List>();
    
            foreach (var item in collections)
            {
                maxLength = Math.Max(item.Count(), maxLength);
                if(collections.Any())
                    enumerators.Add(item.GetEnumerator());
            }
            // Set enumerators to first item
            enumerators.ForEach(e => e.MoveNext());
    
            var result = new List();
            for (int i = 0; i < maxLength; i++)
            {
                // Add elements to result collection
                enumerators.ForEach(e => result.Add(e.Current));
    
                // Remobve enumerators, in which no longer have elements
                enumerators = enumerators.Where(e => e.MoveNext()).ToList();
            }
    
            return result;
        }
    }
    

    Example of using:

    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 result= CollectionsHandling.Merge(a, b, c);
    }
    

    When you understand how it works, it will be possible to reduce the method of smaller.

提交回复
热议问题