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

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

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


当前回答

或者像这样:

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

其他回答

这个问题理解起来有点棘手,但我猜问题是在遍历键时试图从Dictionary中删除元素。我认为在这种情况下,你别无选择,只能使用第二个数组。

ArrayList lList = new ArrayList(lDict.Keys);
foreach (object lKey in lList)
{
  if (<your condition here>)
  {
    lDict.Remove(lKey);
  }
}

如果你可以使用泛型列表和字典,而不是数组列表,那么我就会这样做,然而上面的应该是工作的。

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

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

Marc Gravell的答案应该对你有用。myDictionary。Keys返回一个对象,该对象实现了ICollection<TKey>, IEnumerable<TKey>及其非泛型对应项。

我只是想补充一下,如果你计划访问这个值,你可以像这样循环字典(修改的例子):

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

对于混合字典,我使用这个:

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

或者像这样:

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