-1

I need Lambda query to filter dates from list and return Max Date. If the list does not satisfy the filter then should return a null value. This is my code, need a shorter version ->

var a = Dates.Where(x => x >= DateTime.Now).Select(x => x);
if(a.Count > 0)
{
  return a.Max();
}
else return null;

The value returned to is in DateTime? format which shows error "Embedded statement cannot be a declaration or labeled statement".

Ankur Rai
  • 297
  • 1
  • 5
  • 19
  • Use a ternary operator – codejockie Nov 30 '17 at 20:45
  • Why do you need a shorter version? You probably do need a version that compiles, though. `a` doesn't have a `Count` property. It has a `Count()` method -- which as Eric is about to suggest, isn't a very good approach anyhow. You just want to know if it's got *any* items in it. – 15ee8f99-57ff-4f92-890c-b56153 Nov 30 '17 at 20:46
  • 4
    I have a jar that can contain any number of pennies. My question to you is: are there any pennies in the jar? Now, think about it: **do you have to count the pennies in order to answer the question**? – Eric Lippert Nov 30 '17 at 20:47
  • 4
    Why is there a trivial select on the end of the query? That makes no sense. – Eric Lippert Nov 30 '17 at 20:48
  • 1
    Possible duplicate of [Max return value if empty query](https://stackoverflow.com/questions/6966680/max-return-value-if-empty-query) – mjwills Nov 30 '17 at 20:49
  • can you show the method signature and it's return type where the code sits in.. update / edit your question to show it.. also is your return type declared a `Nullable` you would need to return `(Nullable)null` or `default(DateTime?)` need more information / code.. – MethodMan Nov 30 '17 at 20:49

1 Answers1

1
var Dates = new List<DateTime>();

DateTime? max = Dates.Where(x => x >= DateTime.Now)
    .Select(x => (DateTime?) x)
    .DefaultIfEmpty(null)
    .Max();

Console.WriteLine(max == null ? "null" : "not null");

You need to cast the result to Nullable<DateTime> one way or another, if your list is composed of DateTime.

Edit : as @RogerStewart mentioned in comments, to perform the cast you could use Cast<DateTime?>() instead of the Select statement.

Pac0
  • 21,465
  • 8
  • 65
  • 74