Search code examples
c#linq

linq .Value Nullable Object must have a value. How to skip?


I have some linq code that is sometimes null:

        cbo3.ItemsSource = empty.Union(from a in
                                           (from b in CompleteData
                                            select b.TourOpID).Distinct()
                                       select new ComboBoxItemString() { ValueString = a.Value.ToString() });

But TourOpID is sometimes null throwing an error on a.Value.ToString() . How do I solve this?


Solution

  • The problem occurs because you access the Value property of a Nullable type which is null (or, more precisely, whose HasValue property is false). How to fix this depends on what you want to do:

    1. If you want to filter out items where TourOpID is null, just add a where clause:

      ...
      (from b in CompleteData
       where b.TourOpID != null         // filter
       select b.TourOpID).Distinct()
      ...
      
    2. If you want to use a replacement value, e.g. 0, if TourOpID is null, use the null coalescing operator ??, which converts your int? into an int:

      ...
      (from b in CompleteData
       select b.TourOpID ?? 0).Distinct()
      ...
      

      or, alternatively,

      ...
      select new ComboBoxItemString() { ValueString = a.GetValueOrDefault().ToString() });
      
    3. If you just want to show a different ComboBox entry if TourOpID is null, use the ternary operator ?::

      ...
      select new ComboBoxItemString() { 
          ValueString = (a == null ? "no tour operator" : a.Value.ToString())
      });
      

      If you want to show the empty string if a is null, the solution is even simpler:

      ...
      select new ComboBoxItemString() { ValueString = a.ToString() });
      

      since Nullable.ToString returns an empty string if it does not have a value.