我只想要字典的键而不是值。
我还没能得到任何代码来做这个。使用另一个数组被证明是太多的工作,因为我使用删除也。
我如何在字典中获得键的列表?
我只想要字典的键而不是值。
我还没能得到任何代码来做这个。使用另一个数组被证明是太多的工作,因为我使用删除也。
我如何在字典中获得键的列表?
你应该可以只看。
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的答案应该对你有用。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);
}
这个问题理解起来有点棘手,但我猜问题是在遍历键时试图从Dictionary中删除元素。我认为在这种情况下,你别无选择,只能使用第二个数组。
ArrayList lList = new ArrayList(lDict.Keys);
foreach (object lKey in lList)
{
if (<your condition here>)
{
lDict.Remove(lKey);
}
}
如果你可以使用泛型列表和字典,而不是数组列表,那么我就会这样做,然而上面的应该是工作的。
或者像这样:
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);
}
更新。net 3.5+
获取所有键的列表:
using System.Linq;
List<String> myKeys = myDict.Keys.ToList();
如果您在使用系统时遇到任何问题。Linq,见如下:
Visual Studio不识别系统。Linq 系统。Linq命名空间
对于混合字典,我使用这个:
List<string> keys = new List<string>(dictionary.Count);
keys.AddRange(dictionary.Keys.Cast<string>());
我经常使用这个来获取字典中的键和值:
For Each kv As KeyValuePair(Of String, Integer) In layerList
Next
(layerList类型为Dictionary(of String, Integer))
我真不敢相信这些令人费解的答案。假设键的类型是:string(或者使用'var'如果你是一个懒惰的开发人员):-
List<string> listOfKeys = theCollection.Keys.ToList();