Search code examples
c#listalphabetical

Merging a List<string> into another one alphabetically


Say I have a (not so well ordered) master list:

List<string> list1 = new List<string> { "AB2", "AB1", "AB3", "BB3", "BB2", "BB1" };

I want to add another list to it in alphabetical order. For example, if I have

List<string> list2 = new List<string> { "AA1", "AA2", "BA1", "BA2" };

The merged list would be

List<string> listMerged = new List<string> { "AA1", "AA2", "AB2", "AB1", "AB3", "BA1", "BA2", "BB3", "BB2", "BB1" };

So the rule, in loose terms, would be: for each element of the master list, loop the second list and insert each element that is found alphabetically before.

How can I achieve this? I don't want the first list to be sorted, I just want to insert the second one in it ordered accordingly.


Solution

  • This code will give you the output you asked for.

    For each item in the second list, it will compare it to an item from the first list, moving front to back through the first list. If the comparison is positive, so B > A, it will keep iterating. Otherwise, it will stop and insert into the first list before the item it compared to.

    var list1 = new List<string> { "AB2", "AB1", "AB3", "BB3", "BB2", "BB1" };
    var list2 = new List<string> { "AA1", "AA2", "BA1", "BA2" };
    
    foreach (var item in list2)
    {
        var index = 0;
        while (index < list1.Count && item.CompareTo(list1[index]) > 0)
        {
            index++;
        }
        list1.Insert(index, item);
    }