mihai
mihai

Reputation: 2804

Remove list elements at given indices

I have a list which contains some items of type string.

List<string> lstOriginal;

I have another list which contains idices which should be removed from first list.

List<int> lstIndices;

I'd tried to do the job with RemoveAt() method ,

foreach(int indice in lstIndices)
{
     lstOriginal.RemoveAt(indice);
}

but it crashes and said me that "index is Out of Range."

Upvotes: 19

Views: 47728

Answers (7)

ghord
ghord

Reputation: 13797

My in-place deleting of given indices as handy extension method. It copies all items only once so it is much more performant if large amount of indicies is to be removed.

It also throws ArgumentOutOfRangeException in case where index to remove is out of bounds.

 public static class ListExtensions 
 {
    public static void RemoveAllIndices<T>(this List<T> list, IEnumerable<int> indices)
    {
        //do not remove Distinct() call here, it's important
        var indicesOrdered = indices.Distinct().ToArray();
        if(indicesOrdered.Length == 0)
            return;

        Array.Sort(indicesOrdered);

        if (indicesOrdered[0] < 0 || indicesOrdered[indicesOrdered.Length - 1] >= list.Count)
            throw new ArgumentOutOfRangeException();

        int indexToRemove = 0;
        int newIdx = 0;

        for (int originalIdx = 0; originalIdx < list.Count; originalIdx++)
        {
            if(indexToRemove < indicesOrdered.Length && indicesOrdered[indexToRemove] == originalIdx)
            {
                indexToRemove++;
            }
            else
            {
                list[newIdx++] = list[originalIdx];
            }
        }

        list.RemoveRange(newIdx, list.Count - newIdx);
    }
}

Upvotes: 2

daryal
daryal

Reputation: 14919

 lstIndices.OrderByDescending(p => p).ToList().ForEach(p => lstOriginal.RemoveAt((int)p));

As a side note, in foreach statements, it is better not to modify the Ienumerable on which foreach is running. The out of range error is probably as a result of this situation.

Upvotes: -2

phoog
phoog

Reputation: 43046

How are you populating the list of indices? There's a much more efficient RemoveAll method that you might be able to use. For example, instead of this:

var indices = new List<int>();
int index = 0;
foreach (var item in data)
    if (SomeFunction(data))
        indices.Add(index++);

//then some logic to remove the items

you could do this:

data.RemoveAll(item => SomeFunction(item));

This minimizes the copying of items to new positions in the array; each item is copied only once.

You could also use a method group conversion in the above example, instead of a lambda:

data.RemoveAll(SomeFunction);

Upvotes: 6

alex.b
alex.b

Reputation: 4567

        var array = lstOriginal.ConvertAll(item => new int?(item)).ToArray();
        lstIndices.ForEach(index => array[index] = null);
        lstOriginal = array.Where(item => item.HasValue).Select(item => item.Value).ToList();

Upvotes: 1

YoryeNathan
YoryeNathan

Reputation: 14512

for (int i = 0; i < indices.Count; i++)
{
    items.RemoveAt(indices[i] - i);
}

Upvotes: 5

Omaha
Omaha

Reputation: 2292

The reason this is happening is because when you remove an item from the list, the index of each item after it effectively decreases by one, so if you remove them in increasing index order and some items near the end of the original list were to be removed, those indices are now invalid because the list becomes shorter as the earlier items are removed.

The easiest solution is to sort your index list in decreasing order (highest index first) and then iterate across that.

Upvotes: 5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

You need to sort the indexes that you would like to return from largest to smallest in order to avoid removing something at the wrong index.

foreach(int indice in lstIndices.OrderByDescending(v => v))
{
     lstOriginal.RemoveAt(indice);
}

Here is why: let's say have a list of five items, and you'd like to remove items at indexes 2 and 4. If you remove the item at 2 first, the item that was at index 4 would be at index 3, and index 4 would no longer be in the list at all (causing your exception). If you go backwards, all indexes would be there up to the moment when you're ready to remove the corresponding item.

Upvotes: 49

Related Questions