我有一个在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 :(得分: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
}
在阅读您的评论后,我建议您可以使用ref或out变量
public void SetStoreInfoDetail(int issueID, ref Dictionary<int, StoreInfo> theDict)
然后会这样调用
StoreInfoMapping = new Dictionary<int, StoreInfo>();
SetStoreInfoDetail(id, ref StoreInfoMapping);
在方法本身中,您可以使用传入的字典,而不是实例化字典,所做的任何更改都将反映在方法之外。
答案 1 :(得分: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);
}
}