Alex
Alex

Reputation: 38509

Querying two collections at same time with Linq

If I have 2 collections of objects, is it possible to effectively join them, and select from both of them, in one query?

For example:

var collection1 = GetSomeData();
var collection2 = GetSomeMoreData();

var myResult = from x in collection1
               from y in collection2
               where x.SomeProperty = "Yes"
               where y.SomeProperty = "Yes"
               select x, select y;

GetSomeData, and GetSomeMoreData both return IEnumerable<MyType>

Obviously this doesn't compile... but hopefully it gives an illustration of what I'm trying to do the idea...

Upvotes: 3

Views: 1502

Answers (1)

Ani
Ani

Reputation: 113402

I think you want Enumerable.Concat:

var myResult = collection1.Concat(collection2)
                          .Where(x => x.SomeProperty == "Yes");

or in query-syntax:

var myResult = from x in collection1.Concat(collection2)
               where x.SomeProperty == "Yes"
               select x;

Note that the word 'join' you use, in the context of LINQ, normally refers to finding (and pairing / grouping up) common elements between two sequences based on some key. That's not what you intend to do, is it?

Upvotes: 8

Related Questions