0

I would like to test for null to avoid exception. I receive list of objects which i have to export to excel and display in Grid.Mvc

Excel export:

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.

Q1: For the excel export, my solution is to use a couple of if/else (any better way)?

For the Grid display: if/else or "?" operator is not supported inside the 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

Q2: Any idea how to solve this?

Maro
  • 2,579
  • 9
  • 42
  • 79
  • 2
    Possible duplicate of [Shorthand for nested null checking C#](http://stackoverflow.com/questions/2831439/shorthand-for-nested-null-checking-c-sharp) – MakePeaceGreatAgain Jul 14 '16 at 08:59

3 Answers3

5

If you're using C#6 (which is included in VS2015, thanks HimBromBeere.), you can write it as followed:

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

If any of the properties is NULL, the result will be NULL.

Tom Wuyts
  • 855
  • 1
  • 11
  • 27
  • 1
    This is a feature of C#6, not .NET. However the language comes only on VS2015 which usually is used on .NET 4.6. You could use this feature also on .NET 2.0 when using VS2015. Anyway nice answer. – MakePeaceGreatAgain Jul 14 '16 at 09:08
  • Null propagation operator or "Elvis operator" on of the best syntax sugar in C# – Alex Jul 14 '16 at 09:48
2

As for Q2: You can use statement lambdas by enclosing the statement in curly braces: https://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");
xaggre
  • 128
  • 6
1

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");
Eugen Kotov
  • 504
  • 4
  • 16