linq .Value可为空的对象必须具有一个值.如何跳过? [英] linq .Value Nullable Object must have a value. How to skip?

查看:220
本文介绍了linq .Value可为空的对象必须具有一个值.如何跳过?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些linq代码,有时是null:

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() });

但是TourOpID有时nulla.Value.ToString()上引发错误.我该如何解决?

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

推荐答案

发生此问题是因为您访问Nullable类型的Nullable类型的="noreferrer"> Value属性(或更准确地说,其HasValue属性为false).如何解决此问题取决于您要执行的操作:

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. 如果要过滤出TourOpID为null的项目,只需添加where子句:

  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()
...

  • 如果要使用替换值,例如0,如果TourOpID为空,请使用空合并运算符 ??,它将您的int?转换为int:

  • 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()
    ...
    

    或者,或者,

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

  • 如果在TourOpID为null的情况下只想显示另一个ComboBox条目,请使用三元运算符?::

  • 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())
    });
    

    如果要在a为null时显示空字符串,则解决方案甚至更简单:

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

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

    因为 Nullable.ToString 返回空字符串(如果没有)有一个值.

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

    这篇关于linq .Value可为空的对象必须具有一个值.如何跳过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆