views:

33

answers:

1

In our application we have a little query that looks like this:

var selectedAgents = from agent in listAgents
    where (this.collectionVehicles.GetVehicleByAgent(agent)).IsActive || 
          (this.collectionVehicles.GetVehicleByAgent(agent)).IsSoldSinceCurrentSession 
           select agent;

This works fine but the method GetVehicleByAgent is called two times and this is maybe not necessary.

Before LINQ we had a foreach-loop and did like this:

Vehicle parentVehicle = collectionVehicles.GetVehicleByAgent(agent);

if (parentVehicle.IsActive || parentVehicle.IsSoldSinceCurrentSession)
{
    selectedAgents.Add(agent);
}

As you can see GetVehicleByAgent returns a Vehicle object and that can easiely compared more than once. So I am looking for a way the retieve the Vehicle inside the LINQ query and keep it. I don't want to call GetVehicleByAgent twice.

+4  A: 

You need to use the let clause, like this:

var selectedAgents =
    from agent in listAgents
    let parentVehicle = collectionVehicles.GetVehicleByAgent(agent)
    where parentVehicle.IsActive || parentVehicle.IsSoldSinceCurrentSession 
    select agent;
SLaks
Yes, that's it! Works perfect!
Holli