Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge result IQueryable<T> together?

Tags:

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); 
like image 258
KentZhou Avatar asked Dec 14 '09 16:12

KentZhou


People also ask

How do I combine two IQueryable results?

var list4 = list1. Union(list2); Union is a set operation - it returns distinct values. Concat simply returns the items from the first sequence followed by the items from the second sequence; the resulting sequence can include duplicate items.

How do I join two LINQ queries?

LINQ Join queries. As we know the JOIN clause is very useful when merging more than two table or object data into a single unit. It combines different source elements into one and also creates the relationship between them. Using the join, you can grab the data based on your conditions.

What inherits from IQueryable?

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed.

What is the difference between IEnumerable T and IQueryable T?

The major difference between IQueryable and IEnumerable is that IQueryable executes query with filters whereas IEnumerable executes the query first and then it filters the data based on conditions.


2 Answers

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

like image 103
Yuriy Faktorovich Avatar answered Sep 25 '22 16:09

Yuriy Faktorovich


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.

like image 41
Adriaan Stander Avatar answered Sep 24 '22 16:09

Adriaan Stander