Question

With:

var q1 = (IQueryable<T>).....;
var q2 = (IQueryable<T>).....;
var q3 = (IQueryable<T>).....;

var qList = new List<IQueryable<T>>{q1, q2, q3};

I want to do this:

var q = q1.Union(q2).Union(q3);

But using qList instead of using q1, q2 and q3. I tried with qList.SelectMany but the behavior is different (the queryables are queries to a database and SelectMany makes a query for each queryable instead of just one query).

Was it helpful?

Solution

You can use the Aggregate extension method:

var q = qList.Aggregate((x, y) => x.Union(y));

Or following Thomas Levesque's suggestion:

var q = qList.Aggregate(Queryable.Union);

This will pick the first item from qList, union it with the second item, union the result with the third item, and so on for each item in qList. Note that this would not actually involve evaluating any of the IQueryable<T>'s, just constructing a new IQueryable<T> which represents a union of the others.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top