Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine multiple lists with custom sequence

Tags:

c#

algorithm

list

Not sure if there's a algorithm to describe this problem but are there any elegant methods to combine the list in a custom sequence. For example:

List<string> list1 = new List<string>();
List<string> list2 = new List<string>();
List<string> list3 = new List<string>();

list1.Add("a");
list1.Add("b");
list1.Add("c");

list2.Add("d");
list2.Add("e");
list2.Add("f");

list3.Add("g");
list3.Add("h");
list3.Add("i");

List<string> combined = new List<string>();

I would like the contents of combined to contain a sequence as follows:

a //First record in list1
d //First record in list2
g //First record in list3
b //Second record in list1
e //Second record in list2
h //Second record in list3
c //Third record in list1 
f //Third record in list2 
i //Third record in list3 

The number of records in each list may not be equal.

EDIT

When the number of records in each list may not be equal i mean:

List<string> list1 = new List<string>();
List<string> list2 = new List<string>();
List<string> list3 = new List<string>();

list1.Add("a");

list2.Add("b");
list2.Add("c");

list3.Add("d");
list3.Add("e");
list3.Add("f");

List<string> combined = new List<string>();

Expected results:

a //First record in list1
b //First record in list2
d //First record in list3
c //Second record in list2
e //Second record in list3
f //Third record in list3
like image 822
atp03 Avatar asked Mar 14 '13 09:03

atp03


1 Answers

Not sure if there's a name. Merging? Splicing? But the code is easy.

var lists = new [] { list1, list2, list3 };
var combined = new List<string>(lists.Sum(l => l.Count));    

for (var i = 0; i < lists.Max(l => l.Count); i++)
{
   foreach (var list in lists)
   { 
      if (i < list.Count)
          combined.Add (list[i])
   }
}
like image 78
Tim Rogers Avatar answered Sep 30 '22 13:09

Tim Rogers