How to reorder the evaluation of this Linq script

Here is a code snippet

IEnumerable<Car> GetCars()
{
   foreach(var request in RequestQueue())
   {
       RemoveFromQueue(request);
       yield return MakeCar(request);//Expensive
   }
}

      

// Using scenario 1: No problem

foreach(Car c in GetCars())
{
//Do stuff
}

      

// Using scenario 2: problem, I've built all the cars, but I only want 1.

foreach(Car c in GetCars().Where(p=>p.Request.Id==10000))
{
 //Do stuff
}

      

Is it possible to implement an evaluation of the Where clause before going further and making a car? How?

Obviously the where clause can change depending on the use of the client.

Motivation . When you execute Linq to SQL, .Take (10) is converted to Top (10) and the query is executed on the server. I want to achieve something similar.

0


a source to share


2 answers


@ J.13.L's suggestion is probably the best practical one: expose an API that one car will receive.

However, the answer to your last question on how .Take (10) is in the TOP 10 on SQL Server is that you need to implement an IQueryable provider and parse an expression tree. It's not very trivial, but if you're interested in learning how, there are tons of articles on how to do it here:



+1


a source


Not sure without seeing the rest of the code, but what's stopping you from doing this?

Car GetCar(id)
{
    Car result = default(Car);

    // I am assuming that RequestQueue() is Enumerable?
    Request request = RequestQueue().SingleOrDefault(p => p.Request.Id == id);

    if(result != null)
    {
        RemoveFromQueue(request);

        result = MakeCare(request);
    }

    return result;
}

      



Then use that method instead of GetCar () and // Do Something, but it's hard to see if this will work without seeing more code. Hope this helps ...

0


a source







All Articles