简体   繁体   中英

Performing a JOIN in LINQ in C#

I am writing some C# that has some entities. My entities are:

Address        Store
-------        -----
ID             ID
StreetAddress  AddressID
City           Name
State

I need to do a LINQ query that gives me all of the stores for a certain city. Currently, I have:

var addresses = await Address.GetFromDatabase();
var results = address in addresses
              where (address.City == 'Seattle')
              select new
              {
                StoreID = store.ID
                StoreAddress = address.StreetAddress
              }

This code obviously does not work. The join to Store does not exist. However, because Store must also hit the database, I'm not sure what to do. I appreciate any help you can give.

You can do joins in LINQ and it's pretty straightforward:

var results = from address in addresses
              join store in stores
              on address.ID equals store.AddressID
              where (address.City == 'Seattle')
              select store;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM