C#将两个不均匀的列表交织到新列表中 [英] C# interweave two uneven List into a new List

查看:57
本文介绍了C#将两个不均匀的列表交织到新列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,两个列表的长度都不同.我要实现的是第三个List,它包含list1的第一个元素,然后是list2的第一个元素,然后是list1的第二个元素,以及list2的第二个元素,依此类推,直到用尽了两个元素(它们都是(不均匀),然后只需添加该列表中的所有剩余项.

I have two List, both of different lengths. What I am trying to achieve is a third List that contains the first element from list1, then the first element from list2, then second element from list1, and second element from list2, and so on until one of the two has been exhausted (they're uneven), and then just add in any remaining items from that list.

结果的项目数应与list1和list2的总和相同.

result should have the same number of items as list1 and list2 combined.

我不能使用诸如Union.ToList()之类的东西,因为那样不会使两者交织,它只会将例如list1的所有项目添加到list2的底部,并将其作为结果输出.我尝试了.Zip(Linq),但是它似乎吸收了两个元素并将它们合并为一个元素(即将两个字符串连接为一个更长的字符串).

I cannot use something like Union.ToList() as that doesn't interweave the two, it just adds all of the items from for example list1 to the bottom of list2 and outputs it as result. I tried .Zip(Linq) however that seems to take in the two elements and merged them into a single element (namely concatenating the two strings into one longer string).

List<string> list1 = new List<string>(){
            "4041",
            "4040"              
        };

List<string> list2 = new List<string>(){ 
            "4039",
            "4044", 
            "4075", 
            "4010",
            "4100",
            "4070", 
            "4072" 
        };


// Ideal result:    
result = { "4041",
      "4039",
      "4040"  
      "4044",      
      "4075", 
      "4010",
      "4100",
      "4070", 
      "4072" 
}; 

推荐答案

int length = Math.Min(list1.Count, list2.Count);

// Combine the first 'length' elements from both lists into pairs
list1.Take(length)
.Zip(list2.Take(length), (a, b) => new int[] { a, b })
// Flatten out the pairs
.SelectMany(array => array)
// Concatenate the remaining elements in the lists)
.Concat(list1.Skip(length))
.Concat(list2.Skip(length));

这篇关于C#将两个不均匀的列表交织到新列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆