How to check if the LINQ expression does not come null

Asked

Viewed 800 times

3

I have this expression LINQ:

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

My problem is that images. First(i => i.Ismainimage == true) can return null if you have no image with the property Ismainimage marked as true. What is the best way to check if null is given and use another equality to put a value on mainImage?

1 answer

3


Utilize FirstOrDefault, if there is no return it returns the default value of the class that is null (This varies according to type, if it is a int for example the return is 0 as default value).

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

That one Default of the method of is the same thing as 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);
    }
}

Exit:

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

Online Example

References:

  • What he’ll get if he goes Default?

  • @ihavenokia made the edit, if he does not find return null!

  • Okay, so the difference is that with the Default he keeps null instead of giving Exception?

  • The OrDefault checks if there has been a return if it does not give a default(T) where T is the return type, which in your case is a class and every class the default value is null I’ll improve the answer.

  • 1

    I’ve seen the changes, it’s 5* :)

  • @ihavenokia vlw

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.