简体   繁体   English

检查多个子对象为null的最佳方法

[英]Best way to check for null for multi child object

I would like to test for null to avoid exception. 我想测试null以避免异常。 I receive list of objects which i have to export to excel and display in Grid.Mvc 我收到必须导出到excel并在Grid.Mvc中显示的对象列表

Excel export: Excel导出:

sheet.Cells["A" + i].Value = item.Car.Door.Code; //FLCo

Grid display: 网格显示:

columns.Add(c => c.Car.Door.Code).Titled("FLCo");

The thing is Car can be null, Door can be null. 事情是Car可以为空, Door可以为空。

Q1: For the excel export, my solution is to use a couple of if/else (any better way)? Q1:对于excel导出,我的解决方案是使用几个if/else (更好的方法)吗?

For the Grid display: if/else or "?" 对于网格显示: if/else或“?” operator is not supported inside the linq LINQ中不支持运算符

the following will generate error 以下将产生错误

columns.Add(c => c.Car==null?"":(c.Car.Door==null?"":c.Car.Code)).Titled("FLCo");

error: 错误:

Cannot convert lambda expression to type 'GridMvc.Columns.IGridColumn' because it is not a delegate 无法将Lambda表达式转换为类型'GridMvc.Columns.IGridColumn',因为它不是委托

Q2: Any idea how to solve this? Q2:知道如何解决吗?

If you're using C#6 (which is included in VS2015, thanks HimBromBeere.), you can write it as followed: 如果您使用的是C#6(感谢VS2015,它包含在VS2015中),则可以按以下方式编写:

sheet.Cells["A" + i].Value = item?.Car?.Door?.Code;

If any of the properties is NULL, the result will be NULL. 如果任何属性为NULL,则结果将为NULL。

As for Q2 : You can use statement lambda s by enclosing the statement in curly braces: https://msdn.microsoft.com/de-de/library/bb397687.aspx#Anchor_1 至于Q2 :您可以通过将语句括在花括号中来使用statement lambdahttps : //msdn.microsoft.com/de-de/library/bb397687.aspx#Anchor_1

So in your case it would be 所以在你的情况下

columns.Add(c => {c.Car==null?"":(c.Car.Door==null?"":c.Car.Code)}).Titled("FLCo");

You can use "Elvis operator" . 您可以使用“猫王运算符” Or if not supported I prefer to use extension methods. 或者,如果不支持,我更喜欢使用扩展方法。

public static class Maybe
{
    public static TResult With<TInput, TResult>
        (this TInput o, Func<TInput, TResult> evaluetor)
        where TInput : class
        where TResult : class
    {
        return o == null ? null : evaluetor(o);
    }

    public static TResult Return<TInput, TResult>
        (this TInput o, Func<TInput, TResult> evaluator, TResult failureValue)
        where TInput : class
    {
        return o == null ? failureValue : evaluator(o);
    }
}

So in code you can just do something like 所以在代码中,您可以做类似

sheet.Cells["A" + i].Value = item.With(x => x.Car).With(x => x.Door).Return(x => x.Code, "null");

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

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