我一直在閱讀很多關于如何使用 foreach 迭代 Dictionary 的檔案,但我不太明白如何通過它所具有的級別。例如:
我有“params”字典,我向其中添加字串和物件值,使用.Add(),并在其中一個中添加一個名為“item”的級別。
據我了解,使用 Foreach(KeyValueaPair<>) 是遍歷字典。我是否需要使用另一個 foreach(KeyValuePair<>) 才能遍歷第二級?
比如我想讓“param”獲取Posnr帶來的元素的值
IDictionary<string, object> params = new Dictionary<string, object>();
params.Add("Customerid", zwCustomer.Customerid);
params.Add("PedidoCli", zwCustomer.PedidoCli);
params.Add("PedidoSap", zwCustomer.PedidoSap);
params.Add("TFacturaMat", new Dictionary<string, object>()
{
{
"item", new Dictionary<string, object>()
{
{"Vbeln", zfacturaMats.Vbeln},
{"Posnr", zfacturaMats.Posnr},
{"Matnr", zfacturaMats.Matnr},
}
},
});
foreach(KeyValuePair<string, object> item in parametros)
{
param = $"{item.Key} : {item.Value}";
}
uj5u.com熱心網友回復:
不,你可以直接這樣做。Dictionary<TKey, TValue>.NET 庫的類已經為您做了所有這些魔術。
使用 foreach 回圈
foreach(KeyValuePair<string, object> item in params)
{
Console.WriteLine($"{item.Key} : {item.Value}");
}
您已經遍歷了字典的所有元素。從使用的角度來看,這與 params 是一個 List 完全相同(除了沒有保證的順序)。
如果你想要一個特定的元素,你有多種可能性,但在最簡單的情況下,你可以通過var myValue = params["PosNr"]. 或者,您可以使用該TryGetValue()方法來測驗是否存在某個鍵。
所以底線:知道字典在內部是如何作業的很有趣,但是當您使用 .NET 庫時,您不必關心這些。開箱即用的迭代和訪問作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476106.html
下一篇:我可以在C#中有兩個入口點嗎
