简体   繁体   English

linq .Value Nullable Object必须具有值。 怎么跳?

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

I have some linq code that is sometimes null : 我有一些有时为null linq代码:

        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() . 但是TourOpID有时是null的抛出一个错误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 ). 出现此问题的原因是您访问Nullable类型的Value属性 ,该属性null (或者更准确地说,其HasValue属性为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: 如果要过滤掉TourOpID为null的项,只需添加where子句:

     ... (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 ?? 如果要使用替换值,例如0 ,如果TourOpID为null,请使用空合并运算符 ?? , which converts your int? ,转换你的int? into an int : 进入一个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 ?: : 如果您只想在TourOpID为null时显示不同的ComboBox条目,请使用三元运算符?: ::

     ... 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: 如果要显示空字符串,如果a为null,则解决方案甚至更简单:

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

    since Nullable.ToString returns an empty string if it does not have a value. 因为Nullable.ToString返回一个空字符串,如果它没有值。

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() . 为什么不使用ValueString = a.ToString()而不是ValueString = a.Value.ToString() If a has a value it will return this value to string, if not - a.ToString() will return empty string. 如果a有一个值,它会将此值返回给字符串,否则 - a.ToString()将返回空字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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