Linq statement returns null
I have following statement
EmployeeLog objEmpployeeLog =
lstEmployeeLog.Where(x => x.EmpId == iEmpId
&& x.InDateTime.Value == lastCheckInDate
&& x.OutDat开发者_Go百科eTime == 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.
My guess would be small difference (seconds, millis,etc) between x.InDateTime.Value
and lastCheckInDate
. Try rounding them off to some pre-determined precision.
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.
I am assuming you are using a nullable DateTime value for OutDateTime, if you are change
x.OUtDateTime == null to !x.OutDateTime.HasValue
精彩评论