我只想要字典的键而不是值。

我还没能得到任何代码来做这个。使用另一个数组被证明是太多的工作,因为我使用删除也。

我如何在字典中获得键的列表?


当前回答

你应该可以只看。

    Dictionary<string, int> data = new Dictionary<string, int>();
    data.Add("abc", 123);
    data.Add("def", 456);
    foreach (string key in data.Keys)
    {
        Console.WriteLine(key);
    }

其他回答

更新。net 3.5+

获取所有键的列表:

using System.Linq;

List<String> myKeys = myDict.Keys.ToList();

如果您在使用系统时遇到任何问题。Linq,见如下:

Visual Studio不识别系统。Linq 系统。Linq命名空间

List<string> keyList = new List<string>(this.yourDictionary.Keys);

你应该可以只看。

    Dictionary<string, int> data = new Dictionary<string, int>();
    data.Add("abc", 123);
    data.Add("def", 456);
    foreach (string key in data.Keys)
    {
        Console.WriteLine(key);
    }

我真不敢相信这些令人费解的答案。假设键的类型是:string(或者使用'var'如果你是一个懒惰的开发人员):-

List<string> listOfKeys = theCollection.Keys.ToList();

或者像这样:

List< KeyValuePair< string, int > > theList =
    new List< KeyValuePair< string,int > >(this.yourDictionary);

for ( int i = 0; i < theList.Count; i++)
{ 
  // the key
  Console.WriteLine(theList[i].Key);
}