LINQ joining values from different classes
c#, lambda, linq
Solution
You're extremely close! Using your code (and making all properties on House and Person public), here is a method using the LINQ Join method:
var st = GetAllHouses().Join(GetAllPersons(),
outerKey => outerKey.PersonId,
innerKey => innerKey.ID,
(house, person) => new
{
house.ID,
house.Address,
house.ZipCode,
PersonFirstName = person.FirstName,
PersonLastname = person.LastName
});
Note: I would recommend the GetAllPersons() and the GetAllHouses() methods return IQueryable rather than IEnumerable. Doing so will build the expression (including the join), which means LINQ-to-SQL (or Entities) will build a proper SQL statement with the JOIN included, instead of enumerating the collections and then joining.
Additional information on such can be found here: Returning IEnumerable<T> vs. IQueryable<T>
Problem
I am new to LINQ and sorry if my question have been asked I have 2 classes ``` public class Person { int ID {get;set;} string FirstName {get;set;} string LastName {get;set;} } ``` and ``` public class House { int ID {get;set;} string Address {get;set;} string ZipCode {get;set;} int PersonId {get;set;} } ``` I am saving the list of houses in a IEnumerable List ``` IEnumerable<House> ListHouses = GetAllHouses(); ``` GetAllHouses return the list of houses from the database I want to use Lamda select in LINQ in order to do the following ``` var st = ListHouses .Select(h => new { id = h.ID, Address= h.Address, Zip= h.ZipCode , PersonFirstName = GetPersonByID(h.PersonId ).FirstName, PersonLastname = GetPersonByID(h.PersonId ).lastname }); ``` Where GetPersonByID returns an object of Type `Person` that has the given ID. and then I take his first name and last name. My question is this: Instead of Getting the Person 2 times for the variables (personFirstName and PersonLastName) Is there a way I can get it one time and then used it. Something like ``` PersonForId = GetPersonByID(h.PersonId) PersonFirstName = PersonLastName.FirstName, PersonLastname = PersonLastName.lastname ``` I'm looking for something similar to Join in SQL where you join a value from another table. Thanks you very much for any help