Amani
Amani

Reputation: 11

Read null DateTime from null list

I'm try to read Null dateTime from null List using Mvc5

List<TelecomPayments> telPayments = 
    db.TelecomPayments
        .Where(t => t.TelecomAdmin.TelecomAdminID == telecomAdmin.TelecomAdminID)
        .ToList();

telPayments.FirstOrDefault();
DateTime? lastDate = telPayments.FirstOrDefault().ToDate;

if (lastDate == null)
{
    if (telPayments.Count == 0)
    {
    }
}

this what I specify in controller but still through an expiation

Upvotes: 0

Views: 64

Answers (2)

Peter B
Peter B

Reputation: 24280

If you are using C# 6 or higher, then you can use the ?. aka "null conditional" operator:

List<TelecomPayments> telPayments = 
    db.TelecomPayments
        .Where(t => t.TelecomAdmin.TelecomAdminID == telecomAdmin.TelecomAdminID)
        .ToList();

DateTime? lastDate = telPayments.FirstOrDefault()?.ToDate;

This will only try to access .ToDate if the part before it is not null.

If you are on an older C# version then you will have to do a more explicit null check:

List<TelecomPayments> telPayments = 
    db.TelecomPayments
        .Where(t => t.TelecomAdmin.TelecomAdminID == telecomAdmin.TelecomAdminID)
        .ToList();

DateTime? lastDate = null;
var payment = telPayments.FirstOrDefault();
if (payment != null) lastDate = payment.ToDate;

Upvotes: 0

Harald Coppoolse
Harald Coppoolse

Reputation: 30502

When using LINQ there are two groups of functions: those that return IEnumerable<...> (or IQueryable<...>), and those the return a TResult.

If you compose a LINQ statement, always make sure that all intermediate LINQ statements return IEnumerable/IQueryable, only the last one may be FirstOrDefault, ToList, Max, Any, etc.

DateTime? lastDate = telPayments
    .Select(telpayment => telpayment.ToDate)
    .FirstOrDefault();

Simple comme bonjour!

Upvotes: 1

Related Questions