Mah*_*din 0 c# asp.net generics collections
我想解析我的Hashtable使用DictionaryEntry并读取对象的值DictionaryEntry(如果该值是)List<string>
下面是示例代码。
Hashtable strResx = new Hashtable();
List<string> allDetails = new List<string>();
allDetails.Add("val0");
allDetails.Add("val1");
strResx.Add(1, allDetails);
strResx.Add(2, allDetails);
strResx.Add(3, allDetails);
foreach (DictionaryEntry entry in strResx)
{
string value0 = entry.Value.ToString();
string value1 = entry.Value.ToString();
someFunction(value0, , value1);
}
Run Code Online (Sandbox Code Playgroud)
我真的很困惑如何对entry.Value.ToString();
类似entry.Value[0].ToString();和这样的东西进行索引entry.Value[1].ToString();
请帮助。
您可以将值转换为List<string>类型:
foreach (DictionaryEntry entry in strResx)
{
var value = (List<string>)entry.Value;
string value0 = value[0];
string value1 = value[1];
someFunction(value0, value1);
}
Run Code Online (Sandbox Code Playgroud)
如果您要循环插入条目,则可以在 foreach 循环中自动执行此转换Values:
foreach (List<string> value in strResx.Values)
{
string value0 = value[0];
string value1 = value[1];
someFunction(value0, value1);
}
Run Code Online (Sandbox Code Playgroud)
但考虑使用泛型Dictionary<int,List<string>>而不是Hashtable. 这将为您提供类型安全(即,不会有类型值不同于 的字典条目List<string>)和强类型键和值:
var strResx = new Dictionary<int,List<string>>();
// ...
strResx.Add(1, allDetails);
strResx.Add(2, allDetails);
strResx.Add(3, allDetails);
foreach (var kvp in strResx)
{
string value0 = kvp.Value[0];
string value1 = kvp.Value[1];
someFunction(value0, value1);
}
Run Code Online (Sandbox Code Playgroud)
笔记:
allDetails向所有哈希表条目添加相同的列表IndexOutOfRange异常| 归档时间: |
|
| 查看次数: |
2546 次 |
| 最近记录: |