Filipe Borges
Filipe Borges

Reputation: 2783

Single link query where clause to take only `n` of each type from a single model/table

Having a table Entities with a column type (between other columns) how can I select only n entities from type A and m entities from type b in a single linq query where clause? Is it possible?

I am looking for something like this:

var x = from s in db.Entities
        where s.type == `A` && (????) < n 
           || s.type == `B` && (????) < m 
        select s

Current solution with combined queries:

var x = entities.Where(e => e.type == `A`).Take(n).Union(
        entities.Where(e => e.type == `B`).Take(m));

Upvotes: 2

Views: 54

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

You could use GroupBy:

var x = db.Entities.GroupBy(x => x.type)
                   .Where(g => g.Key == "A" || g.Key == "B")
                   .SelectMany(g => g.Key == "A" ? g.Take(n) : g.Take(m));

But I don't know why you don't like your Union-based solution - it should result in just one query sent to the database anyway.

Upvotes: 1

Related Questions