25

If I get two result IQueryable from different linq Query and I want to merge them together and return one as result, how to to this? For example, if:

var q1 = (IQueryable<Person>).....;
var q2 = (IQueryable<Person>).....;

how to merge q1 and q2 together and get result like

var q = (IQueryable<Person>)q1.Union(q2);
KentZhou
  • 24,805
  • 41
  • 134
  • 200

4 Answers4

27

You have it, q1.Union(q2). The Union is in the System.Linq namespace with Queryable.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
  • 4
    Correct me if I'm wrong but IMO in this solution it must be taken into account that the union parameter is IEnumerable, thus it won't do the Union in the database. Furthermore it will call twice at the database because the parameter is an IEnumerable and even though one pass an IQueryable it will be executed as another call to the database. Just wanted to point this out if performance is an issue on the on-memory-union or the calls to the database – fmaccaroni Feb 14 '17 at 21:40
  • 2
    @fmaccaroni I came to this question because I thought the exact same thing. I then did a quick test in LINQPad 5 which *should* be using LINQ-to-SQL. `q1.Union(q2)` produces `SELECT * FROM (SELECT * FROM q1 UNION SELECT * FROM q2)`. So, LINQ casts the `IEnumerable` parameter back to `IQueryable` somewhere under the covers. – Zach Mierzejewski Oct 04 '17 at 20:56
18

You can try the Concat Method

Something like this

int[] i1 = new int[] { 1, 2, 3 };
int[] i2 = new int[] { 3, 4 };
//returns 5 values
var i3 = i1.AsQueryable().Concat(i2.AsQueryable());
//returns 4 values
var i4 = i1.AsQueryable().Union(i2.AsQueryable());

Union will only give you the DISTINCT values, Concat will give you the UNION ALL.

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
2
(q1.Union(q2)).AsQuerable()
amarsuperstar
  • 1,783
  • 1
  • 17
  • 22
2

With NHibernate Union is not possible.

You have to process on the client side instead of DB processing the union. I convert IQueryable to IENumerable with AsEnumerable and then use Concat extension.

var allItems = q1.AsEnumerable().Concat(q2)

Regards, Sebastian

Sebastian Widz
  • 1,962
  • 4
  • 26
  • 45