Linq to SQL lambda join

I am having trouble with this, I tried a few examples, but I just don't get it. This makes sense using a method other than lambda, but how do I make a connection using lambda expressions?

var myCats = GetAllCats(); var myHouses = GetAllHouses(); // pseudosql: select * from a inner join b on a.id = b.id 

I tried this:

 var fullData = myCats.Join(myHouses, a => a.id, b => b.id, (a, b) => a); 

which I kind of looked at in other examples on SO, but fullData is an IEnumerable<Cat> , so I can’t get any properties out of the House.

+7
source share
4 answers
 var fullData = myCats.Join( myHouses, cat => cat.id, house => house.id, (cat, house) => new { Cat = cat, House = house }); 

Access via fullData.First().Cat... or fullData.First().House...

+28
source

The problem is that the result of your connection β€” the last parameter of the Join method β€” is Cat , so fullData is of type IEnumerable<Cat> . If you want to access both, return an anonymous type:

 var fullData = myCats.Join(myHouses, a => a.id, b => b.id, (a, b) => new { Cat = a, House = b}); 
+6
source

This is because the last argument (a, b) => a means displaying the return result only for cats, i.e. (cat, house) => cat

You can return a temporary object with a pair, for example.

 (cat, house) => new { cat, house } 
+5
source

You need to determine what exactly you want to choose from them.

You can change the latter:

 var fullData = myCats.Join(myHouses, cat => cat.id, house => house.id, (cat, house) => new {cat, house}) 

which will make fullData IQueryable of an anonymous type that looks like this:

 class anonymous { Cat cat, House house } 

Equivalent in LINQy format:

 from cat in myCats join house in myHouses on cat.id equals house.id select new {cat, house} 

You can also indicate what you want to choose to avoid waste:

 from cat in myCats join house in myHouses on cat.id equals house.id select new {cat.id, cat.name, house.address} 
+5
source

All Articles