Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining The Results Of Two Linq Queries Into A Single Var?

Tags:

c#

linq

I have two different databases that contain two tables with the exact same design. How do I combine the results from these two queries most efficiently? I know I can put the results of each into a dictionary or array or whatever, but I would like to think that there is a simpler way to do this.

var db1 = //A database object connected to database1
var db2 = //A database object connected to database2

var result1 = db1.table.where(a=>a.value>0);
var result2 = db2.table.where(a=>a.value>0);

var resultSum = result1+result2; //???

Thanks!

Addendum: Concat or Union, which is better for this particular case and why? Thanks!

like image 892
sooprise Avatar asked Mar 08 '11 17:03

sooprise


2 Answers

You can only combine enumerations of the same type, you could project both to a common class and then concatenate them:

var result1 = db1.table.Where(a=>a.value>0).Select( x=> new Foo() { /*set props*/ });
var result2 = db2.table.Where(a=>a.value>0).Select( x=> new Foo() { /*set props*/ });

var resultSum = result1.Concat(result2);
like image 124
BrokenGlass Avatar answered Oct 30 '22 10:10

BrokenGlass


var resultUnion = Enumerable.Union(result1, result2)

or, using the externsion method syntax,

var resultUnion = result1.Union(result2);
like image 27
Ilya Kogan Avatar answered Oct 30 '22 09:10

Ilya Kogan