1

I have a List of nodes, where each node has some coordinates.

public class Node
{
    float x,y;
    ....
}
List<Node> myNodeList;

I need to remove each node from the list that has a distance less of a given threshold from its adjacent nodes. I read this post explaining how remove elements from a collection while iterating it.

I'd prefer using RemoveAll way, instead of iterating the list in reverse order because I think it's cleaner and more elegant. My problem is that I need to access the adjacent elements of the current item, to calculate the distance.

Is there any clean way to do that?

I need something like:

myNodeList.RemoveAll(item => DistanceLessThanThreshold (item.Value, nextNode) && DistanceLessThanThreshold (item.Value, prevNode);

Is that possible?

Community
  • 1
  • 1
Heisenbug
  • 38,762
  • 28
  • 132
  • 190
  • If it gets too ugly, write your own extension method in order to maintain style. – Erix Sep 24 '12 at 15:13
  • 1
    You're going to have some edge cases here. For instance, if you remove the 4th item in the list, then what used to be the 5th item is now the 4th item. Should this new 4th item be using the 3rd item as previous, or should it be using the removed 4th item? I'm not trying to solve your problem, I'm just bringing up this fact because your post doesn't cover things like this, so someone else's idea of a solution might not be your idea of a solution. – Seth Flowers Sep 24 '12 at 15:15
  • @seth flowers: yes I know about edge case. I was just wondering if there is a way to access adjacent elements while iterating. I think it would be nice. – Heisenbug Sep 24 '12 at 15:17
  • Is it feasible to maintain two lists, one containing the data for the iteration and the second containing the results of the operations? This way you aren't modifying the iterated list. – Justin Skiles Sep 24 '12 at 15:31
  • @Justin Skiles: well, I know how to do that. But my question is explicetly reguarding accessing adjacents elements while iterating. I know how to do that in other way (actually, I already did it). – Heisenbug Sep 24 '12 at 15:41
  • @Heisenbug I'm not sure how with lambdas, but you can index into a List just like an array with [] operator. So you could just [index-1] or [index+1] to access the adjacent elements to the current index. – Justin Skiles Sep 24 '12 at 17:02

1 Answers1

1

Instead of removing while iterating you could use a reverse where and create a new list by writing an extension method removewhere as suggested in -

linq remove item from object array where property equals value

Ofcourse if creating a new list is acceptable - depending upon how large the list is!

Community
  • 1
  • 1
NiladriBose
  • 1,849
  • 2
  • 16
  • 31