【问题标题】:Read the value of DictionaryEntry object if the value is List<string>如果值为 List<string>,则读取 DictionaryEntry 对象的值
【发布时间】:2017-08-07 13:26:21
【问题描述】:

我想使用DictionaryEntry 解析我的Hashtable 并读取DictionaryEntry 对象的值(如果值为List&lt;string&gt;) 下面是示例代码。

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);
}

我真的很困惑如何对entry.Value.ToString(); 进行索引 类似entry.Value[0].ToString();entry.Value[1].ToString();

请帮助。

【问题讨论】:

    标签: c# asp.net generics collections


    【解决方案1】:

    您可以将值转换为List&lt;string&gt; 类型:

    foreach (DictionaryEntry entry in strResx)
    {
        var value = (List<string>)entry.Value;
        string value0 = value[0];
        string value1 = value[1];
        someFunction(value0, value1);
    }
    

    如果您将循环通过 Values insted 的条目,您可以在 foreach 循环中自动执行此转换:

    foreach (List<string> value in strResx.Values)
    {    
        string value0 = value[0];
        string value1 = value[1];
        someFunction(value0, value1);
    }
    

    但请考虑使用通用Dictionary&lt;int,List&lt;string&gt;&gt; 而不是Hashtable。这将为您提供类型安全(即不会有类型值不同于 List&lt;string&gt; 的字典条目)和强类型键和值:

    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);    
    }
    

    注意事项:

    • 您正在向所有哈希表条目添加相同的 allDetails 列表
    • 考虑检查entry值是否不为null
    • 考虑检查条目值是否有足够的项目以避免IndexOutOfRange异常

    【讨论】:

      【解决方案2】:

      在你的情况下,你可以使用类似的东西:

      foreach (DictionaryEntry entry in strResx)
      {
          var list = (List<string>)entry.Value;
          string value0 = list[0];
          string value1 = list[1];
          someFunction(value0, value1);
      }
      

      【讨论】:

        猜你喜欢
        • 2022-12-17
        • 1970-01-01
        • 1970-01-01
        • 2017-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-11
        • 1970-01-01
        相关资源
        最近更新 更多