How do I get the list of keys in a Dictionary?

后端 未结 9 815
梦谈多话
梦谈多话 2020-12-02 11:38

I only want the Keys and not the Values of a Dictionary.

I haven\'t been able to get any code to do this yet. Using another array proved to be too much work as I use

相关标签:
9条回答
  • 2020-12-02 12:09

    You should be able to just look at .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);
        }
    
    0 讨论(0)
  • 2020-12-02 12:10

    Marc Gravell's answer should work for you. myDictionary.Keys returns an object that implements ICollection<TKey>, IEnumerable<TKey> and their non-generic counterparts.

    I just wanted to add that if you plan on accessing the value as well, you could loop through the dictionary like this (modified example):

    Dictionary<string, int> data = new Dictionary<string, int>();
    data.Add("abc", 123);
    data.Add("def", 456);
    
    foreach (KeyValuePair<string, int> item in data)
    {
        Console.WriteLine(item.Key + ": " + item.Value);
    }
    
    0 讨论(0)
  • 2020-12-02 12:20

    Or like this:

    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);
    }
    
    0 讨论(0)
  • 2020-12-02 12:23

    To get list of all keys

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

    System.Linq is supported in .Net framework 3.5 or above. See the below links if you face any issue in using System.Linq

    Visual Studio Does not recognize System.Linq

    System.Linq Namespace

    0 讨论(0)
  • 2020-12-02 12:23

    I can't believe all these convoluted answers. Assuming the key is of type: string (or use 'var' if you're a lazy developer): -

    List<string> listOfKeys = theCollection.Keys.ToList();
    
    0 讨论(0)
  • 2020-12-02 12:24

    For a hybrid dictionary, I use this:

    List<string> keys = new List<string>(dictionary.Count);
    keys.AddRange(dictionary.Keys.Cast<string>());
    
    0 讨论(0)
提交回复
热议问题