在Lambda表达式中使用三元运算符 [英] Using Ternary Operator within Lambda Expression

查看:925
本文介绍了在Lambda表达式中使用三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

var now = DateTime.Now;
var firstOfMonth = new DateTime(now.Year, now.Month, 1, 0, 0, 1);

var objectsAfterFirstOfThisMonth= _context.DataObjects
    .Where(x => x.dateClosed == null ? x.dateClosed : x.dateCreated > firstOfMonth);

我收到以下编译错误:

'System.Nullable'和'bool'之间没有隐式转换

There is no implicit conversion between 'System.Nullable' and 'bool'

我对lambda语法的理解不足以理解此错误.

I don't understand the lambda syntax enough to understand this error.

如果我无法使用此三元语法,则将需要我从数据库中获取DataObjects的完整列表,然后遍历此列表,创建过滤后的列表(日期晚于当前月份的那些对象) ).

If I am unable to use this ternary syntax, then I will be required to get the full list of DataObjects from database, then iterate through this list, creating the filtered list (those objects with dates later than the first of current month) as I go.

简而言之,我的目标是:我想获取本月初之后出现的所有对象. dateCreated字段永远不会为null. dateClosed有时为null. dateClosed更准确,我想尽可能地比较该日期,但是如果dateClosed为null,则需要回退到dateCreated.

My goal in a nutshell is this: I want to get all objects that occured after the first of this month. dateCreated field is never null. dateClosed is sometimes null. dateClosed is more accurate and I want to compare on that date as much as possible, but need to fall back on dateCreated in case dateClosed is null.

如果需要提供更多信息,请告诉我.

Please let me know if I need to provide more information.

提前谢谢!

推荐答案

虽然我相信@TyCobb发布了您遇到问题的正确原因,但我不确定他的回答是否会为您提供所需的查询.看来您想获取一个日期并将其与firstOfMonth进行比较?

While I believe @TyCobb posted the correct reason why you are having an issue, I am not sure his answer will give you the query you are looking for. It seems you want to get a date and compare it to firstOfMonth?

如果是这样,我想您可能想要这样的东西:

If so, I think you might want something like this:

var objectsAfterFirstOfThisMonth= _context.DataObjects
    .Where(x => (x.dateCreated != null ? x.dateCreated.Value : x.dateClosed) > firstOfMonth);

这篇关于在Lambda表达式中使用三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆