2016-11-09 12 views
0

定義我這是在SetStoreInfoDetail定義字典詞典循環:如何通過不同的方法

public void SetStoreInfoDetail(int issueID) 
     { 

      _mgr = new CRCManager(); 

      StoreInfo StoreInfoFields = new StoreInfo(); 

      List<StoreInfo> StoreList = _mgr.GetStoreList(issueID); 


      var StoreInfoMapping = StoreList.ToDictionary(keySelector: row => row.store_info_id); 
} 

我想通過StoreInfoMapping循環:

目前代碼:

foreach (StoreInfo store_info_id in StoreInfoMapping) 
{ 
Do Something 
} 

我在這裏做錯了什麼?任何暗示讚賞。

+0

字典需要在範圍內。你可以從方法中返回字典。 – itsme86

+0

有幾種方法可以執行此操作,具體取決於代碼的結構。邏輯流程如何從第一個代碼片段轉到第二個代碼片段? – David

回答

0

你已經實例化了一個字典(StoreInfoMapping)作爲你的方法中的最後一件事,它然後被未使用和處置。要解決這個

一種方法是有一個Dictionary<key,value>作爲方法的返回類型

public Dictionary<int,StoreInfo> SetStoreInfoDetail(int issueID) 

,然後在其中創建變量可以退貨嗎

return StoreList.ToDictionary(keySelector: row => row.store_info_id); 

最後,在代碼中你想參考它你可以做到這一點

//your id = id in this example and the dictionary is assumed to be an <int, StoreInfo> 
StoreInfoMapping = SetStoreInfoDetail(id) 

foreach (StoreInfo store_info_id in StoreInfoMapping) 
{ 
    //Do Something 
} 

readin摹您的意見,我會建議,而不是你可以使用ref或out變量

public void SetStoreInfoDetail(int issueID, ref Dictionary<int, StoreInfo> theDict) 

這將被調用,而不是實例字典,像這樣

StoreInfoMapping = new Dictionary<int, StoreInfo>(); 
SetStoreInfoDetail(id, ref StoreInfoMapping); 

方法本身,你可以使用傳入的內容,所做的任何更改都會反映在方法之外。

+0

我無法將方法類型更改爲public Dictionary SetStoreInfoDetail(int issueID),因爲它會與我在其他地方使用的其他邏輯衝突。 – Programmermid

+0

@Programmermid現在如何? –

0

嘗試循環使用字典:

foreach (KeyValuePair<int,StoreInfo> info in StorInfoMapping) 
{ 
    //Key is the store_info_id 
    //Value is the StoreInfo object   
} 

如果你想用其他方法來訪問字典。

class StoreInfoClass //Your class 
{ 
    //Define dictionary here so it can be accessed by all function within the class 
    private Dictionary<int,StoreInfo> StoreInfoMapping; 

    //Your Functions 
    public void SetStoreInfoDetail(int issueID) 
    { 

     _mgr = new CRCManager(); 

     StoreInfo StoreInfoFields = new StoreInfo(); 

     List<StoreInfo> StoreList = _mgr.GetStoreList(issueID); 


     StoreInfoMapping = StoreList.ToDictionary(keySelector: row => row.store_info_id); 
    } 
} 
+0

是的,但我的字典是用另一種方法定義的。所以我正在尋找一種方法來從另一種方法調用字典。 – Programmermid

+0

您可以在兩個函數都可以訪問的類中創建一個變量(字典),或者使此當前函數SetStoreInfoDetail(int issueID)返回一個字典。 – Jawad