Help streamlining a LINQ query?


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 => ? x.Cars.OrderByDescending(y => => : x.Cars.OrderByDescending(y => : 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 =>" 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