Using Ternary Operator within Lambda Expression

◇◆丶佛笑我妖孽 提交于 2019-12-08 08:05:59

问题


Here is my code:

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);

I get the following compile error:

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

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

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.

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.

Thanks in advance!


回答1:


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);



回答2:


....Where(x => x.dateCreated == null ? x.dateCreated : x.dateClosed > firstOfMonth);

The predicate must evaulate to a bool. Your x.dateCreated is a DateTime? (assumption). You have to do something in the true part that evaluates to a true/false.

Something like the following should get it to compile, but only as an example. I am not sure what your actual logic is supposed to be since you say dateCreated is never null, but you are checking null. Just note that these all evaluate to a true/false value.

....Where(x => x.dateCreated == null ? 
                       x.dateCreated.HasValue :
                       x.dateClosed > firstOfMonth);


来源:https://stackoverflow.com/questions/25924102/using-ternary-operator-within-lambda-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!