简体   繁体   中英

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?

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, eg 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.

where

from b in CompleteData where b.TourOpID != null select b.TourOpID

Why don't You just use ValueString = a.ToString() instead of ValueString = a.Value.ToString() . If a has a value it will return this value to string, if not - a.ToString() will return empty string.

IEnumerable<decimal?> arr = new List<decimal?>
                                            {
                                                1m, 4m, null, 10m, 6m
                                            };

foreach (var @decimal in arr)
{
       Console.WriteLine(@decimal.ToString());
}

The output is:

1
4

10
6

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