NCCSBIM071
NCCSBIM071

Reputation: 1205

Linq statement returns null

I have following statement

    EmployeeLog objEmpployeeLog = 
             lstEmployeeLog.Where(x => x.EmpId == iEmpId 
                    && x.InDateTime.Value == lastCheckInDate 
                    && x.OutDateTime == null).FirstOrDefault();

lstEmpAttnLog is a List, i know it contains the object which has EmpId, InDateTime equal to the argument passed and OutDateTime is null. I saw these values using breakpoint.

I am surprised why it doesn't return the value.

Please help, i am clueless, please guess what could might have gone wrong.

Upvotes: 0

Views: 1131

Answers (3)

Dan Abramov
Dan Abramov

Reputation: 268215

FirstOrDefault returns null if no such element is found.
Therefore, you query doesn't match any item.

As Marc pointed out, perhaps your dates don't match in seconds or milliseconds.
You can modify query to look with specific precision:

var epsilon = TimeSpan.FromSeconds(1.0);
var logItem = employeeLog.Where(x => x.EmpId == empId 
    && (x.InDateTime.Value - lastCheckInDate) < epsilon
    && x.OutDateTime == null).FirstOrDefault();

And please, don't use Systems Hungarian in C# code! It's absolutely pointless, seeing that C# has strong type system and Visual Studio is an advanced IDE.

Upvotes: 2

Aducci
Aducci

Reputation: 26634

I am assuming you are using a nullable DateTime value for OutDateTime, if you are change

x.OUtDateTime == null to !x.OutDateTime.HasValue

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062492

My guess would be small difference (seconds, millis,etc) between x.InDateTime.Value and lastCheckInDate. Try rounding them off to some pre-determined precision.

Upvotes: 3

Related Questions