var readingCustomers = allCustomers
.Where(c => c.Profile != null &&
c.Profile.DefaultShippingAddress != null &&
c.Profile.DefaultShippingAddress.Town == "Reading");
可以簡化成:
var readingCustomers = allCustomers
.Where(c => c.Profile?.DefaultShippingAddress?.Town == "Reading");
再來一個很適合用的例子:XML
string authorName = book.Element("author")?.Attribute("name")?.Value;
如果有 author 元素,且它也有 name 屬性,就回傳,否則就是 null。