Reputation: 20995
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
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
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
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