0

I am writing a fluid simulation in which I need, for each particle, a list of neighboring particles within a radius, R.

If have a list of potential neighbors, how would I remove all the potential neighbors based on a distance criteria?

I am currently doing this with a for loop but this seems slow and inefficient.
My current method in psuedo code is:

temp = getPotentialNeighbors(point);

        foreach(Particle n in temp)
        {
            if(Distance(n.Pos,point.Pos)<radius)
                neighbors.Add(n);
        }
KMoore
  • 171
  • 1
  • 10

1 Answers1

2

If you would like to get all the items that match the predicate and put them into a new list, you can do it like that:

var newList = temp.Where(p => Distance(p,point) < radius).ToList();

To remove the items from the temp list, you can do like that:

temp.RemoveAll(p => Distance(p,point) < radius); 

This passes a predicate to RemoveAll() and it will remove all items that match the condition given by the predicate.

Regarding performance I don't think this would be any better than your version with a loop, but this is shorter and easier.

msporek
  • 1,187
  • 8
  • 21
  • The list is storing a class called Particle, so you have to access the position from the class. I tried this `temp.RemoveAll(x => Distance(point.Pos,x.Pos)' does not contain a definition for 'Pos' and no extension method 'Pos' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?)" – KMoore Dec 30 '14 at 12:40
  • `x.Pos` should be the `radius` argument you supplied yourself in your sample code in the question. – Jan Köhler Dec 30 '14 at 12:54
  • So you want to get a list of Pos properties from the objects? You can use the Select() LINQ mechanism like this: var newList = temp.Where(p => Distance(p,point) < radius).Select(p => p.Pos).ToList(); This will return you a list of Pos properties from the objects. – msporek Dec 30 '14 at 12:55
  • @msporek No, I want to get a list of the potential neighbors their Pos is within a certain radius – KMoore Dec 30 '14 at 12:59