Smithy
Smithy

Reputation: 2190

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?

Upvotes: 12

Views: 40419

Answers (4)

Thusitha Wijerathne
Thusitha Wijerathne

Reputation: 19

summaryViewModel.MisroutedCount = documentQueryList.Where(p => (p.IsMisrouted == null ? false : p.IsMisrouted == true) && (p.ModifiedDateTime == null ? false : p.ModifiedDateTime.Value.Date == DateTime.Now.Date)).ToList().Count;

Upvotes: -1

Dmytro
Dmytro

Reputation: 17196

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

Upvotes: 1

Heinzi
Heinzi

Reputation: 172478

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.

Upvotes: 20

dkozl
dkozl

Reputation: 33394

use where

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

Upvotes: 1

Related Questions