Christian Gollhardt
Christian Gollhardt

Reputation: 17004

Select multiple object in one query on a different where clause for each object

I currently have two querys, which share the same complex query, which I only want to execute once:

//Query 1
from together in (...) // ... = Complex query with multiple joins
where together.property == 0
select new { ... }

//Query 2
from together in (...) // ... = Complex query with multiple joins
where together.property > 0
select new { ... }

The problem is, that they have a different where clause. I tried to set the where clause in the select statement, but this only seems to be possible, if I use groupby which I don't need here:

//Don't work
from together in (...) // ... = Complex query with multiple joins
select new {
    //if together would be grouped, this would work. However I need all data without grouping
    //            . Together is not IQueryable so this does not work
    Foo = together.Where(e => e.property == 0).Select(...),
    Bar = together.Where(e => e.property > 0).Select(...)
}

Is it possible to get 2 objects based on a different where clause in one query with LINQ?

Upvotes: 0

Views: 704

Answers (1)

You could query them all, and then split them up, like this

var qry= (
    from together in (...) // ... = Complex query with multiple joins
    where together.property => 0
    select together)
    .ToList();

var result = new {
    Foo = qry.Where(e => e.property == 0).Select(...),
    Bar = qry.Where(e => e.property > 0).Select(...)
};

Upvotes: 1

Related Questions