Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

linq - C# interweave two uneven List into a new List

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.

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

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" 
}; 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...