Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 554 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I get the list of keys in a Dictionary?

#1
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 remove also.

**How do I get a List of the Keys in a Dictionary?**
Reply

#2
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);
}
Reply

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

Reply

#4
The question is a little tricky to understand but I'm guessing that the problem is that you're trying to remove elements from the Dictionary while you iterate over the keys. I think in that case you have no choice but to use a second array.

ArrayList lList = new ArrayList(lDict.Keys);
foreach (object lKey in lList)
{
if (<your condition here>)
{
lDict.Remove(lKey);
}
}
If you can use generic lists and dictionaries instead of an ArrayList then I would, however the above should just work.
Reply

#5
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);
}
Reply

#6
For a hybrid dictionary, I use this:

List<string> keys = new List<string>(dictionary.Count);
keys.AddRange(dictionary.Keys.Cast<string>());
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through