Hello,

My first post here. I have a problem that I'm sure is simple to solve but haven't yet managed to find a solution, hopefully one of you can help me. :-)

I have a list of int arrays which I have filled with numbers.

List<int[]> Numbers = new List<int[]>();    
            Numbers.Add(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 });
            Numbers.Add(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 });
            Numbers.Add(new int[] { 65, 2, 7, 4, 2, 2, 4, 9 });
            Numbers.Add(new int[] { 45, 2, 23, 4, 13, 6, 7, 8 });
            Numbers.Add(new int[] { 1, 5, 876, 4, 5, 67, 7, 8 });

I then pass this list to a function that checks if there are any duplicate items in the Numbers List and removes them. But it doesn't work :-(

public void RemoveDuplicates(List<int[]> Nums)
    for (int i = 0; i <= Nums.Count - 1; i++)
        {
            for (int n = 1; n <= Nums.Count-1; n++)
            {
                if (Nums[i].SequenceEqual(Nums[n]))
                {
                    Nums.RemoveAt(n);
                }
            }
        }
    }

I'm sure it's a simple mistake I'm making but I can't work it out. Any ideas?

Thanks!

Recommended Answers

All 7 Replies

What you are passing is is entire array not elements of those arrays
Click Here
And then when you do Count -1 you have removed last Array from the count

Hi, I pass the whole array because that's what I want to check, I want to see if one array in the list is the same as another array in the list, I don't want to check the individual elements of each array though, just the array as a whole.

If I take away the Count-1 I get an Array out of bounds error. not sure why but the -1 seemed to solve it.

Thank you for your help :)

You cannot remove items while inisde loops, nor for or foreach loop.
You will have to create a new list, where you will put numbers to delete, or indexes of them, and then add the duplicates inside out it. After this is done, you will have to do another loop through this new list and remove numbers from original list.

Thanks Mitja, and Michael. I am going through the various options you have put forward.

Mitja, If I can't remove items while in a loop how do I remove the items from the list in a loop as you have suggested, once I have made a new list?

Hi again,

I've got it working now :) I Followed Michaels advice and am now using a list of lists.

Thanks again :)

@Mitja I already knew you can't remove items while inside foreach, but why not inside for loop?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.