代码之家  ›  专栏  ›  技术社区  ›  codeandcloud

将哈希表中的所有键检索为字符串

  •  2
  • codeandcloud  · 技术社区  · 15 年前

    编码语言是C#3.0

    for循环还是foreach循环是唯一的选择?

    当做,
    纳文杰

    3 回复  |  直到 15 年前
        1
  •  8
  •   Jon Skeet    15 年前

    你真的是说非通用的吗 Hashtable

    string keys = string.Join(",", table.Keys.Cast<object>()
                                             .Select(x => x.ToString())
                                             .ToArray());
    

    可能有更快的方法,但为了可读性,我会选择这种方法。只有当你证明这是一个瓶颈时才进行微优化。

        2
  •  5
  •   Lukas Körfer    5 年前

    您也可以使用 IDictionaryEnumerator

    string text = "";
    IDictionaryEnumerator enumerator = table.GetEnumerator();
    while (enumerator.MoveNext())
    {
       text += enumerator.Key + ", ";
       text += enumerator.Value + "\n";
    }
    
        3
  •  1
  •   Vladimir Kocjancic    6 年前
    table.Keys.OfType<string>().ToArray();