Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check property for null LINQ

Tags:

c#

.net

linq

I have the following code that give me data from database:

var t = (from ula in proxy.eUserLoginAttempts
         where ula.Date >= DateTime.Now && ula.Email.ToLower().Contains("")
         && ula.User != null
         && ula.User.Client != null
         && ula.User.Client.prStatus == 1
         select ula).ToList();

In this case, I would get prStatus from Client entity and I check User and Client object if they are not null. Should I do it or ula.User.Client.prStatus will translate in Inner Join and this check is needless?

like image 300
IFrizy Avatar asked Dec 13 '25 17:12

IFrizy


1 Answers

Answering your direct question: NO, you should test the nullable first... About your code, I really do suggest a readable way:

var t = proxy.eUserLoginAttempts
    .Where(ula => ula.Date >= DateTime.Now)
    .Where(ula => !string.IsNullOrEmpty(ula.Email))
    .Where(ula => ula.User != null)
    .Where(ula => ula.User.Client != null)
    .Where(ula => ula.User.Client.prStatus == 1)
    .ToList();

Or even better with C# 6

var t = proxy.eUserLoginAttempts
    .Where(ula => ula.Date >= DateTime.Now)
    .Where(ula => !string.IsNullOrEmpty(ula.Email))
    .Where(ula => ula.User?.Client?.prStatus == 1)
    .ToList();
like image 66
Caverna Avatar answered Dec 16 '25 07:12

Caverna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!