Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL lambda join

Tags:

c#

linq-to-sql

Having trouble with this, I've tried following several examples but I am just not getting it. It makes perfect sense using the non-lambda way, but how do I do a join using lambda expressions?

var myCats = GetAllCats();
var myHouses = GetAllHouses();

// pseudosql:  select * from a inner join b on a.id = b.id

I have tried this:

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

which I kind of got through looking at other examples on SO, but fullData is type IEnumerable<Cat> so I can't pull any properties from Houses off it.

like image 228
NibblyPig Avatar asked Mar 28 '11 11:03

NibblyPig


People also ask

How do you write IQueryable join using lambda?

1); var join = query1. Join(query2, x => x. ParentId, y => y. ParentId, (query1, query2) => new { query1 , query2 }).

How does LINQ join work?

In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables. In LINQ, explicit join clauses are only required when two source sequences are not tied by any relationship.


1 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....

like image 195
Femaref Avatar answered Sep 21 '22 20:09

Femaref