tags:

views:

119

answers:

4

Let's say there is a list of List<UInt32>

Thus, :

12|12
23|33
33|22
11|22

I need to remove 0th and 2nd element (List<UInt32>). However, when I try to foreach this list and first remove 0th, the List collapses its elements and 1st becomes 0th now.. so I don't want to delete the wrong element, because my another List<int> includes the positions of elements I want to delete.

Anyway, I thought of doing some algorithm for this, but I wonder if there is already solution for this problem.

+6  A: 

Sort the positions list in descending order and remove elements in that order.

foreach (var position in positions.OrderByDescending(x=>x))
   list.RemoveAt(position);
Mehrdad Afshari
Alright, I am not really sure what I should do in here. There is List<int> which contains positions which need to be deleted from the list. Where is that in the piece of code?
Skuta
@Skuta: `positions` is the list of indexes. `list` is the one you want to delete from (it contains the actual data).
Mehrdad Afshari
In other words: delete from the *end* of the list downwards towards 0.
clintp
+1  A: 

You could create a new collection and adding the items that you don't want to remove and then assign the new collection to the original. That may even be faster than RemoveAt if the indices to be removed are in a hashset/dictionary rather than a list.

ggf31416
+1  A: 

If you are using C#3.0 (or greater) you can use the LINQ extension method Where to filter your list.

var source = new List<int> { 1, 2, 3, 4, 5 };
var filter = new List<int> { 0, 2 };

var result = source.Where((n, i) => !filter.Contains(i)) // 2, 4, 5

And if you want it back to a List<int> instead of IEnumerable<int>, just use ToList()

var list = result.ToList();
Samuel
+3  A: 

Are you able to tell which elements you need to remove based on the elements themselves instead of the index? If so, and you want to change the existing list instead of creating a newly filtered one, use:

 list.RemoveAll(x => (whatever - a predicate));

This is more efficient than removing elements one at a time - each element is only moved once. It's also clearer, if the predicate is obvious :)

Jon Skeet