user759792
user759792

Reputation: 61

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.

Upvotes: 1

Views: 2165

Answers (1)

tukaef
tukaef

Reputation: 9224

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)

Upvotes: 8

Related Questions