views:

58

answers:

3

From a List of builtAgents I need all items with OptimPriority == 1 and only 5 items with OptimPriority == 0. I do this with two seperate queries but I wonder if I could make this with only one query.

IEnumerable<Agent> priorityAgents =
from pri in builtAgents where pri.OptimPriority == 1 select pri;

IEnumerable<Agent> otherAgents =
(from oth in builtAgents where oth.OptimPriority == 0 select oth).Take(5);
A: 

If your underlying data structure has indexing, you're probably better off doing it with two queries anyway because it will be using the indexes to retrieve the matching items. If you're asking about how make it one line, you could always put the results together using a Concat.

Otherwise, if you have examine every item, the only way I can think of to still use LINQ and make only one pass through is the following (untested and potentially dangerous):

int zeroesTaken = 0;
IEnumerable<Agent> agents = from a in builtAgents
                            where a.OptimPriority == 1
                                || (a.OptimPriority == 0 && ++zeroesTaken <= 5)
                            select a;

Rather ugly and dangerous since you of course have to make sure you don't touch zeroesTaken anywhere else until after the query has actually run. And I'm not sure it will actually work if the query has to be run more than once!

I'd feel better encapsulating the whole thing in a method that loops through each item in builtAgents and yield returns the matches...

lc
+2  A: 

Concatenate both result using the Concat operator.So its basically a single query

IEnumerable<Agent> priorityAgents =
(from pri in builtAgents where pri.OptimPriority == 1 select pri).Concat((from oth in builtAgents where oth.OptimPriority == 0 select oth).Take(5));
Sachin
A: 

As @Sachin suggests Contat sounds be the better option. You have two different values queries, the strategy isn't the same.

But, just a tip, I really appreciate Lambda Expressions:

IEnumerable<Agent> union = BuiltAgents.Where(p => p.OptimPriority == 1).Concat(BuiltAgents.Where(q => q.OptimPriority == 1).Take(5));
Luís Custódio