Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select both Min & Max across entire query using EF Core?

I'm trying to write a query where it only needs to ping the db once. Currently I have:

var postQuery = context.Posts.Where(...);
var min = postQuery.Min(d => d.Start);
var max = postQuery.Max(d => d.End);

Is there a way to combine this into a single select statement?

like image 533
Alexander Blyth Avatar asked Oct 23 '25 21:10

Alexander Blyth


1 Answers

Ok, it's a bit tricky but here it is:

var result = context.Posts.Where(...)
    .GroupBy(p => 1) // Group by a constant to get a single row result
    .Select(g => new
    {
        MinStart = g.Min(p => p.Start),
        MaxEnd = g.Max(p => p.End)
    })
    .FirstOrDefault();
like image 143
dani herrera Avatar answered Oct 27 '25 03:10

dani herrera