简体   繁体   English

如何在linq中比较可为空的变量?

[英]How to compare nullable variable in linq?

I try to select some data by linq but system shows me this error 我尝试通过linq选择一些数据,但系统显示此错误

Expression of type 'System.DateTime' cannot be used for parameter of type 'System.Object' of method 'Boolean Equals(System.Object)' 类型'System.DateTime'的表达式不能用于方法'Boolean Equals(System.Object)'的类型'System.Object'的参数

My WorkingResults.EffectiveDate is DateTime? 我的WorkingResults.EffectiveDate是DateTime吗? but my date variable is DateTime. 但我的日期变量是DateTime。 How do I change my code to fix this out? 如何更改代码以解决此问题?

  WorkingResult workingResultObj = (from workingResult in this.DataWorkspace.ApplicationData.WorkingResults
where workingResult.EmployeeCode == employeeCode  && workingResult.EffectiveDate.Equals(date)                                         
select workingResult).FirstOrDefault();

Thank you for any help. 感谢您的任何帮助。

Well, there are a couple of workarounds. 好吧,有两种解决方法。 First, you could make it a DateTime: 首先,您可以将其设为DateTime:

workingResult.EffectiveDate.GetValueOrDefault(DateTime.MinValue).Equals(date)

I don't know what a valid date is. 我不知道什么是有效日期。 Or, you could use Object.Equals: 或者,您可以使用Object.Equals:

Object.Equals(workingResult.EffectiveDate, date)

Which may not give you the intended results. 这可能不会给您预期的结果。 If you always know effective date has a value, then you can use @spajce approach. 如果您始终知道生效日期是有价值的,则可以使用@spajce方法。

You can use .HasValue and Its must like 您可以使用.HasValue及其必须

...
where workingResult.EmployeeCode == employeeCode && 
(workingResult.EffectiveDate.HasValue && 
 workingResult.EffectiveDate.Value.Date == date.Date).FirstOrDefault();
 WorkingResult workingResultObj = 
  (
      from workingResult 
      in this.DataWorkspace.ApplicationData.WorkingResults
      where 
            workingResult.EffectiveDate.HasValue
            && workingResult.EmployeeCode == employeeCode  
            && workingResult.EffectiveDate.Value == date                                         
      select workingResult
  ).FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM