简体   繁体   中英

How can I use the conditional null operator to check for null string?

I'm trying to execute the LINQ to objects query as follows:

var c1 = allCustomers
    .Where(x => x.CompanyName.Replace("'", "").StartsWith(searchText))
    .ToList();

This works fine as long as CompanyName is not null.

So, I thought this seems like the perfect place for the new null conditional operator! Just change to:

var c1 = allCustomers
    .Where(x => x.CompanyName?.Replace("'", "").StartsWith(searchText))
    .ToList();

and everything should work!

Instead, I get the error:

Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

I'm not quite sure how to accomplish what I want here. How would I use the null conditional in this scenario?

You need a coalesce operator to convert the tri-state to a proper boolean.

var c1 = allCustomers
    .Where(x => x.CompanyName?.Replace("'", "").StartsWith(searchText) ?? false)
    .ToList();

I call bool? a tri-state because it can have three values: true , false and null ; therefore, converting bool? to bool is a narrowing conversion that requires explicit treatment.

you need more question marks! i think you need null coalescing as well, since x.CompanyName?.Replace could now also return null.

(x.CompanyName?.Replace("'", "") ?? string.Empty).StartsWith(searchText))

the ?? string.empty ?? string.empty forces that to be a non-null string, which now supports .startswith

Use ?? operator like:

Where(x => x.CompanyName?.Replace("'", "").StartsWith(searchText) ?? false)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM