Help streamlining a LINQ query?

Hi,

I've been writing a lot of queries lately that do a lot of null checking and "navigation" of the database so to speak, and the queries I've been writing have been very repetitious and embedded, so I'm hoping someone here might know if there's a more streamlined way of doing something like this:

car = x.Cars.Any() ? x.Cars.OrderByDescending(y => y.date).FirstOrDefault().NewCars.Any() ? x.Cars.OrderByDescending(y => y.date).FirstOrDefault().NewCars.OrderByDescending(y => y.date).FirstOrDefault().NewCar : x.Cars.OrderByDescending(y => y.date).FirstOrDefault().OldCar : defaultCar; 

(this example is just doing this sort of logic: car = NewCar ?? (OldCar ?? defaultCar);

So the core problem I think is that since the data is spread out across multiple tables, I have to reuse the expression "x.Cars.OrderByDescending(y => y.date).FirstOrDefault()" many times. I'm guessing there's no way to store this as an intermediate variable or something inside of a lambda expression, so is there anything I can do here? Sorry if the example is contrived and hard to understand.

by casey12141 via /r/csharp

Leave a Reply