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 linq 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: