Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete multiple entries from a List without going out of range?

Tags:

c#

I have a list of integers that contains a number of values (say, 200).

List<int> ExampleList;

And another list on integers that holds the indexes that need to be deleted from ExampleList. However, this list is not sorted.

List<int> RemoveFromExampleList;

If it were sorted, I would have run a reverse loop and deleted all the values like this:

for (int i = (RemoveFromExampleList.Count-1); i >=0; i--)
{
    ExampleList.RemoveAt(RemoveFromExampleList[i]);
}

Do I have to sort RemoveFromExampleList, or is there another way to prune the unnecessary values from ExampleList?

If I do have to sort, whats the easiest way to sort? Is there any inbuilt C# library/method to sort?

like image 632
xbonez Avatar asked Oct 05 '10 20:10

xbonez


2 Answers

If RemoveFromExampleList is a list of indexes, you would have to sort it and work in descending order to delete based on those indexes. Doing it any other way would cause you to delete values you don't mean to delete.

like image 59
Andrew Barber Avatar answered Nov 04 '22 03:11

Andrew Barber


Here is the one liner.

ExampleList.RemoveAll(x => RemoveFromExampleList.Contains(ExampleList.IndexOf(x)));
like image 41
RBW_IN Avatar answered Nov 04 '22 03:11

RBW_IN