I never gotten any code I tried to work?. I want to key and not value(yet). Using another array prove to be much work as I use remove also.
+12
A:
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);
}
Marc Gravell
2009-08-14 08:56:35
Thanks man, this works
Jonathan Shepherd
2009-08-14 09:19:43
+2
A:
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);
}
Thorarin
2009-08-14 09:01:55
A:
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.
Dan
2009-08-14 09:07:23
A:
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);
}
Gorhal
2009-09-21 22:07:33