Marco Moschettini
Marco Moschettini

Reputation: 1735

Calling a boolean method inside the where clause of a Linq query

I've a query in Linq that calls a method inside the where clause... Here's the code:

it = {my iter}
{
   ...
   return from l in lifts
          where(compare(l.Trip.Start, it.Start, startRadius)) 
          select l;
}

private bool compare(POI a, POI b, int radius)
{
    return (((b.Position.X.Value - radius < a.Position.X.Value) 
              && (a.Position.X.Value < b.Position.X.Value + radius))
              && ((b.Position.Y.Value - radius < a.Position.Y.Value)
              && (a.Position.Y.Value< b.Position.Y.Value + radius)));
}

but the query returns every time all the lifts list. Why the method compare returns every time true? Where I'm wrong? Thank you

Upvotes: 1

Views: 1398

Answers (1)

user1068352
user1068352

Reputation: 632

There has to be something wrong with your data or compare method. There is nothing magical in how where works. I bet that if you place return false in compare method, returned list will be empty.

Update: you should consider @Jacob Proffitt answer too if you aren't sure of it.Start value at the time of query execution (I don't know why it is down-voted).

Try to replace LINQ query with simple foreach loop and step through code with debugger.

As suggested in comments, in compare method you probably want to measure if two points are within some range. So:

double x1 = a.Position.X.Value; 
double y1 = a.Position.Y.Value; 
double x2 = b.Position.X.Value; 
double y2 = b.Position.Y.Value; 

return ((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)) < (r*r);

Upvotes: 2

Related Questions