【发布时间】:2010-11-19 14:11:39
【问题描述】:
我只想要字典的键而不是值。
我还没有获得任何代码来执行此操作。使用另一个数组被证明是太多的工作,因为我也使用 remove。
如何获取字典中的键列表?
【问题讨论】:
标签: c# list dictionary
我只想要字典的键而不是值。
我还没有获得任何代码来执行此操作。使用另一个数组被证明是太多的工作,因为我也使用 remove。
如何获取字典中的键列表?
【问题讨论】:
标签: c# list dictionary
List<string> keyList = new List<string>(this.yourDictionary.Keys);
【讨论】:
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);
}
【讨论】:
获取所有键的列表:
using System.Linq;
List<String> myKeys = myDict.Keys.ToList();
如果您在使用 System.Linq 时遇到任何问题,请参阅以下内容:
【讨论】:
using System.Linq; 我需要知道哪些答案可以忽略。对不起:)
.ToList() 在我使用了这么多次时会抛出错误,所以我来到这里寻找答案,我意识到我正在使用的文件没有 using System.Linq :)
Dictionary<string, object>.KeyCollection' does not contain a definition for '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);
}
【讨论】:
我无法相信所有这些令人费解的答案。假设密钥的类型为:字符串(如果您是懒惰的开发人员,请使用 'var'):-
List<string> listOfKeys = theCollection.Keys.ToList();
【讨论】:
using System.linq;
这个问题有点难以理解,但我猜问题是您在迭代键时试图从字典中删除元素。我认为在这种情况下你别无选择,只能使用第二个数组。
ArrayList lList = new ArrayList(lDict.Keys);
foreach (object lKey in lList)
{
if (<your condition here>)
{
lDict.Remove(lKey);
}
}
如果您可以使用通用列表和字典而不是 ArrayList,那么我会的,但是上面应该可以正常工作。
【讨论】:
或者像这样:
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);
}
【讨论】:
对于混合字典,我使用这个:
List<string> keys = new List<string>(dictionary.Count);
keys.AddRange(dictionary.Keys.Cast<string>());
【讨论】:
我经常使用它来获取字典中的键和值:(VB.Net)
For Each kv As KeyValuePair(Of String, Integer) In layerList
Next
(layerList 的类型是 Dictionary(Of String, Integer))
【讨论】: