-1

I need to check if FirstOrDefault() is not null, and if not, take some property. My best bet is:

var results = Database.Set<Pizzas>().Select(x => new PizzaViewModel
{
    Base = Database.Set<Bases>().FirstOrDefault(y => y.Id == x.Base.Id) != null ? Database.Set<Bases>().FirstOrDefault(y => y.Id == x.Base.Id).Name : null
}).ToList();

Is there better way to do this?

mazas17
  • 47
  • 5
  • @BalagurunathanMarimuthu Again, that is not a duplicate. Don't throw duplicates that are not an answer to the question. – Patrick Hofman Jul 03 '17 at 10:07
  • This looks like a custom implemented outer join. You might consider read into [outer joining](https://stackoverflow.com/questions/3404975/left-outer-join-in-linq). – Jeroen van Langen Jul 03 '17 at 10:09
  • 1
    @BalagurunathanMarimuthu dublicate you provided doesn't answer my question, since all answers provide similar queries to mine – mazas17 Jul 03 '17 at 10:10

3 Answers3

5

You can use null propagation operator on FirstOrDefault():

Base = Database.Set<Bases>().FirstOrDefault(y => y.Id == x.Base.Id)?.Name
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
3

Since someone mentioned multiple properties I'll add this in, the let allows us to keep the base so that we can query it for multiple things, and the null propagation operator allows us to make sure we're not breaking if there was no base found.

var bases = Database.Set<Bases>();
var results =
    (from pizza in Database.Set<Pizzas>()
    let pizzaBase = bases.FirstOrDefault(pizzaBase => pizzaBase.Id == pizza.Base.Id)
    select new PizzaViewModel {
        Base = pizzaBase?.Name,
        BaseIngredients = pizzaBase?.Ingredients
    }).ToList();
0

You can do it this way for C# < 6.0:

Base = Database.Set<Bases>().Where(y => y.Id == x.Base.Id)
                            .Select(y=> y.Name).FirstOrDefault();

Otherwise, you can use the Null-Conditional Operator (?) operator before .Name

Zein Makki
  • 29,485
  • 6
  • 52
  • 63