Search code examples
c#entity

Enforce FirstOrDefault to return null


I need to return null, if an element is not found in a list, but it returns a empty guid.

mappedTypes.Where(x => x.ReferenceId == new Guid("1a087b71-638c-4f3c-b1cf-3b0438c181c0")).Select(x=>x.MappingId).FirstOrDefault()

This query just returns '00000000-0000-0000-0000-000000000000' - and I want to return null - or a single guid-value if it exists.


Solution

  • You might select it with casting to Guid?:

    mappedTypes.Where(x => x.ReferenceId == new Guid("1a087b71-638c-4f3c-b1cf-3b0438c181c0"))
               .Select(x => (Guid?) x.MappingId)
               .FirstOrDefault();
    

    See also: Nullable types (C# Programming Guide)