Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of a List of IQueryables

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).

like image 604
pomber Avatar asked Dec 30 '25 01:12

pomber


1 Answers

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.

like image 74
p.s.w.g Avatar answered Jan 01 '26 15:01

p.s.w.g