tags:

views:

27

answers:

2

I use this LINQ query in an app I am writing:

internal int GetNoteCount(DateTime startDate, DateTime endDate)
{
    var a = DataStore.ObjectContext.Notes.Where(n => n.LastRevised >= startDate);
    var b = a.Where(n => n.LastRevised <= endDate);
    return b.Count();
}

Obviously, the query gets Notes that fall between two dates. I'd like to simplify the query by consolidating the first two lines into one. I know I can use fluent syntax to add the Count() method call to the end of my query.

Here's my question: How can I consolidate the two queries? Apparently, the && operator doesn't work with two lambda expressions. Thanks for your help.

+3  A: 

You can do this:

internal int GetNoteCount(DateTime startDate, DateTime endDate)
{
    return DataStore.ObjectContext.Notes.Where(n => n.LastRevised >= startDate && n.LastRevised <= endDate).Count();
}

Just use the && on your conditions, not the entire lambda :)

Nick Craver
Don't forget that he's returning the .Count().
Jacob Proffitt
@Jacob - woops, thanks and added :)
Nick Craver
Thanks! Accepted and +1
David Veeneman
+1  A: 

First, there's nothing wrong with the && operator and it should work just fine.

var a = DataStore.ObjectContext.Notes.Where(n => n.LastRevised >= startDate && n.LastRevised <= endDate); 
return a.Count();

Second, with LINQ, it delays performing the query until the .Count() so there is no functional difference between your example and this one.

Jacob Proffitt