Using Ternary Operator within Lambda Expression

2019-05-31 22:53发布

问题:

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