How to check if the LINQ expression does not come null

2

I have this LINQ expression:

MaterialImage mainImage = images.First(i => i.IsMainImage == true);

My problem is that images.First (i => i.IsMainImage == true) can return null if it has no image with the IsMainImage property checked as true. What is the best way to check if you gave null and use another equality to put a value in mainImage ?

    
asked by anonymous 04.01.2017 / 20:31

1 answer

3

Use FirstOrDefault , if it does not return it returns the default value of the class that is null ( this varies according to the type, if it is a int for example the return is 0 as the default value ).

MaterialImage mainImage = images.FirstOrDefault(i => i.IsMainImage == true);
if (mainImage != null)
{ 
     // teve retorno;
}

This Default of the is the same thing that default (T) and as has already been reported depending on the type it puts its default value .

For example:

using System;

public class Carros
{
    public int Id {get;set;}
}

public class Test
{
    public static void Main()
    {
        System.Console.WriteLine(default(int));
        System.Console.WriteLine(default(long));
        System.Console.WriteLine(default(DateTime));
        System.Console.WriteLine(default(Carros) == null);
    }
}

Output:

0
0
1/1/0001 12:00:00 AM
True

Example OnLine

References:

04.01.2017 / 20:33