-1

The code given below is giving the following error when I put a ? or null checker on airUserCreditCardList. cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

bookingInfo.CreditCardList = airUserCreditCardList
    ?.Any(item => item.Text.ToLower().Contains("primary")) 
    ? airUserCreditCardList
        .Distinct()
        .OrderBy(o => o.Text)
        .ToList() 
    : airUserCreditCardList.ToList();

What should the fix for this?

rock rake
  • 5
  • 1
  • Does this answer your question? [cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)](https://stackoverflow.com/questions/22680391/cannot-implicitly-convert-type-bool-to-bool-an-explicit-conversion-exists) – Franz Gleichmann Jul 01 '21 at 12:25
  • 1
    Does this answer your question? [Cannot implicitly convert type bool?](https://stackoverflow.com/questions/9089536/cannot-implicitly-convert-type-bool) – gunr2171 Jul 01 '21 at 12:27

2 Answers2

0

You can check for null before using Any extension:

// assuming airUserCreditCartList is in fact an argument to your method
if (airUserCreditCartList == null) throw new ArgumentNullException(nameof(airUserCreditCardList));

bookingInfo.CreditCardList = airUserCreditCardList
    .Any(item => item.Text.ToLower().Contains("primary")) 
    ? airUserCreditCardList
        .Distinct()
        .OrderBy(o => o.Text)
        .ToList() 
    : airUserCreditCardList.ToList();

Crono
  • 10,211
  • 6
  • 43
  • 75
0

Change it to

        bookingInfo.CreditCardList = airUserCreditCardList
?.Any(item => item.Text.ToLower().Contains("primary")) == true
? airUserCreditCardList
    .Distinct()
    .OrderBy(o => o.Text)
    .ToList() 
: airUserCreditCardList.ToList();

The condition in the "ternary" operator expects a boolean expression. But yours returns a Nullable<bool> aka bool?, because of the "Elvis" operator.

To make it a boolean expression compare the return of "?.Any(...)" to true.

lidqy
  • 1,891
  • 1
  • 9
  • 11