在C#中使用LINQ执行JOIN

时间:2014-10-03 18:21:41

标签: c# linq

我正在写一些有一些实体的C#。我的实体是:

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

我需要做一个LINQ查询,它给我一个特定城市的所有商店。目前,我有:

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

此代码显然不起作用。商店的连接不存在。但是,由于Store也必须访问数据库,因此我不确定该怎么做。我感谢您给予的任何帮助。

1 个答案:

答案 0 :(得分:4)

您可以在LINQ中进行连接,这非常简单:

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