johnny 5
johnny 5

Reputation: 20995

Linq Select items where they are before a certain date or the first after

I have a Linq-to-Entity query which grabs all the items before a certain date, I was wondering if anyone body knows a way to also grab the first record larger than that date in the same query.

context.Items.Where(x => x.CheckDate < DateTime.Now)

Is there a way to modify this so that I can grab the first date after without making two queries?

Upvotes: 0

Views: 2310

Answers (3)

m0r6aN
m0r6aN

Reputation: 908

You don't need to do all of that...

context.Items.Where(x => x.CheckDate < DateTime.Now).OrderByDescending(x => x.CheckDate).FirstOrDefault();

Upvotes: 1

Damith
Damith

Reputation: 63065

var items = from u in context.Items
                                 let dt = (from i in context.Items
                                  where i.CheckDate> DateTime.Now orderby i.CheckDate ).FirstOrDefault()
                                 where u.CheckDate <=dt
                             select u;   

Upvotes: 2

Sajeetharan
Sajeetharan

Reputation: 222582

You need two queries, but to merge the results you can use concat,

var result =context.Items.Where(x => x.CheckDate < DateTime.Now).Concat( context.Items.OrderByDescending(t=>t.CheckDate >Yourdatetime).FirstOrDefault());

Upvotes: 2

Related Questions