簡體   English   中英

Linq連接兩個值

[英]Linq join on two values

假設我有一個{City, State}的列表。 它最初來自數據庫,並且我具有LocationID,但是現在我將其加載到內存中。 假設我還有一張快餐店的桌子,其中有城市和州作為記錄的一部分。 我需要獲取與城市和州匹配的場所列表。

注意:我嘗試描述一種簡化的情況; 我的業務領域是完全不同的。

我想出了以下LINQ解決方案:

var establishments = from r in restaurants
from l in locations
where l.LocationId == id &&
      l.City == r.City &&
      l.State == r.State
select r

我覺得必須有更好的東西。 對於初學者來說,我已經在內存中包含了City / State-因此僅返回數據庫以進行聯接似乎效率很低。 我正在尋找一種說{r.City, r.State} match Any(MyList)是我的City / State集合。

UPDATE我想基於以下建議更新:

List<CityState> myCityStates = ...;
var establishments =
from r in restaurants
join l in myCityStates
    on new { r.City, r.State } equals new { l.City, l.State } into gls
select r;

並且出現以下編譯錯誤: Error CS1941 The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'. Error CS1941 The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.

UPDATE 2編譯器不喜歡聯接中的匿名類。 我說的很明確,但它不再抱怨了。 我會看看它是否真的在早上起作用...

在我看來,您需要這樣做:

var establishments =
    from r in restaurants
    join l in locations.Where(x => x.LocationId == id)
        on new { r.City, r.State } equals new { l.City, l.State } into gls
    select r;

好吧,只要依靠表查找,您就無能為力了,唯一可以加快速度的就是在City和State上建立索引。

linq語句必須轉換為有效的SQL語句,其中“ Any”將轉換為類似以下內容:

SELECT * FROM Restaurants where City in ('...all cities')

我不知道其他ORM是否可以在EF的這類情況下提供更好的性能,但是可能值得研究。 EF從未聽說過讀取速度很快。

編輯:您也可以這樣做:

List<string> names = new List { "John", "Max", "Pete" };
bool has = customers.Any(cus => names.Contains(cus.FirstName)); 

這將產生您正在尋找的必要的IN('value1','value2'...)功能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM