2016-06-15 19 views
2

我有這個疑問查詢太慢 - 獲取和更新記錄使用LINQ查詢

foreach (var item in collection) 
{ 
    var countrylist = from country in countryList 
           where 
            (from state in stateList 
             where 
              (from city in cityList 
              where 
              city.CityID == item.CityID 
              select new 
              { 
               city.CountryID 
              }).Contains(new { StateID = state.StateID }) 
             select new 
             { 
              state.CountryID 
             }).Contains(new { CountryID = country.CountryID }) 
           select new 
           { 
            CountryID = country.CountryIDD, 
            Name = country.Name 
           }; 

       item.Country = new Country(); 
       item.Country.CountryID = countrylist.Select(s => s.CountryID).FirstOrDefault(); 
       item.Country.Name = countrylist.Select(s => s.CountryName).FirstOrDefault(); 
} 

它會根據給定的cityID和CountryId和國家或地區名稱,然後它收集更新相關的對象。現在它運行在一個循環中,目前我有5-10個項目(測試數據)在集合中,並且需要相當長的時間(明顯很慢)。如果5-10項物品緩慢,100+物品的速度太慢。有另一種方法可以讓這件事變得更好嗎?

我會感謝任何形式的幫助

+1

嘗試:https://msdn.microsoft.com/en-us/library/bb311040 .aspx?f = 255&MSPPError = -2147217396 –

+1

首先簡化查詢。如果你不明白它的作用,你不能讓它走得更快。然後檢查缺少的索引。此外,不是對每個項目執行相同的查詢,而是生成item.CityID列表並使用'where itemCities.Contains(city.CityID)'。這轉換爲一個單一的查詢與'IN(...)'子句,而不是5-10慢查詢 –

+0

@MurrayFoxcroft我同意我不知道爲什麼我沒有想到第一個 – Angloos

回答

3

基於Murray Foxcroft的迴應,我建立了一個新的查詢。我沒有你正在使用的對象,但我認爲它應該類似於此:使用代替連接

var countrylist = from country in countryList 
      join state in stateList 
      on country.CountryID = State.CountryID 
      join city in cityList 
      on state.StateID = city.StateID 
      where 
      city.CityID == item.CityID 
      select new 
      { 
       CountryID = country.CountryIDD, 
       Name = country.Name 
      }; 
+0

你偷我的雷霆:)感謝您花時間給OP一個很好的編碼答案。 –

+0

謝謝你的幫助 – Angloos

+0

很高興能幫到你! –

0

我要去猜測,您所在的城市中有一個CountryID場,你不需要加入到一個國家。這是簡單的代碼,沒有任何異常處理:你可能想嘗試找到一個城市,然後在try catch塊中獲得該國家。

foreach (var item in collection) 
    { 
     var country = countryList.Find(c=> c.CountryID == cityList.Find(c => c.CityID == item.CityID).StateId); 
     item.Country = newCountry 
     { 
      CountryID = country.CountryIDD, 
      Name = country.Name 
     }; 
    }; 
+0

城市沒有countryID字段在裏面。國家有州和州有市。所以市有StateID和國家有國家ID – Angloos

+0

啊,根據代碼作出的假設:選擇新 { city.CountryID } – Kell

+0

是啊我同意,我讓它太複雜..我想我睡着了,當我是寫它? – Angloos