0

I am attempting to take two lists, check that they are both in ascending order, and finally merge them into one list that is also in ascending order. for example, if I had {1,2,2,5} and {1,3,4,5,7}, they are in ascending order so they would then join to become {1,1,2,2,3,4,5,5,7}. I think I have figured most of it out but if someone could help me finish it off that would be greatly appreciated!

so far I have:

static List<int> Merge(List<int> myValues, List<int> myValues2)
{
    List<int> merged = new List<int>(myValues.Concat(myValues2));

    for (int i = 0; i <= myValues.Count || i <= myValues2.Count; i++) 
    {
        
        if ((myValues[i] > myValues[i+1]) || (myValues2[i] > myValues2[i+1]))
        {
            Console.WriteLine("lists are not in ascending order");
            System.Environment.Exit(0);
        }
    } return merged;
}

and this in main:

List<int> myValues2 = new List<int>{6, 7, 8, 9, 10};
List<int> myValues = new List<int>{6, 5, 7, 8, 9};
List<int> ret = Merge(myValues2, myValues);

ret.Sort();
Console.WriteLine(string.Join(",", ret));

The main issue I am having is that when the lists are in in the correct order, I receive a "index was out of range" message. I imagine it is to do with i+1, but i don't know how to navigate that issue.

Spawn
  • 935
  • 1
  • 13
  • 32

2 Answers2

0

Yes, I think you are correct about the issue of incrementing the iterator beyond the bound of the list. Perhaps you can handle this with a try{}Catch(){}? Or if this is not elegant enough maybe you can change the conditions in the for loop to test against (MyValues.Count - 1) Since if you reach the last element of the list there is no reason to test its successor?

sog
  • 493
  • 4
  • 13
0

The exception occurs when the count of both the lists are different. Index was out of range exception comes from this line. Here, if either myValues or myValues2 doesn't have the index element then the exception throws.

if ((myValues[i] > myValues[i+1]) || (myValues2[i] > myValues2[i+1])) 
    

It is suggested to have two different loops when the count of both lists are different. And also remove equals condition from the for loop since index is starting at 0.

for (int i = 0; i <= myValues.Count || i <= myValues2.Count; i++)
Siva Makani
  • 196
  • 2
  • 17