提取密钥列表怀疑我的脑子现在不工作 - 我需要提取密钥列表等:尝试从一个.NET字典
Dictionary<string, MyClass> myDict;
List<String> myKeys = myDict.Keys;
第二行编译失败的Keys属性返回一个“KeyCollection”类,而不是关键对象的列表<>。
提取密钥列表怀疑我的脑子现在不工作 - 我需要提取密钥列表等:尝试从一个.NET字典
Dictionary<string, MyClass> myDict;
List<String> myKeys = myDict.Keys;
第二行编译失败的Keys属性返回一个“KeyCollection”类,而不是关键对象的列表<>。
使用LINQ,你可以做以下...
List<String> myKeys = myDict.Keys.ToList();
但是取决于你的目标是什么的钥匙(选择性枚举等),它可能会更有意义与领取钥匙的工作,而不是转换到一个列表。
谢谢 - 这非常漂亮:我需要获得Linq的支持! – winwaed 2011-03-08 16:46:15
是的,你可以尝试 - IEnumerable<String> myKeys = myDict.Keys;
总是一个好主意,用IEnumerable
(更通用的类型)。
如果你需要一个真正的名单:
List<string> myKeys = new List<string>(myDict.Keys);
这会产生运行时错误 – Smith 2012-06-26 10:48:18
KeyCollection实现IEnumerable
接口。
您可以使用扩展方法将其转换为列表。
List<String> myKeys = myDict.Keys.ToList();
或使用不同的构造函数:
List<String> myKeys = new List<String>(myDict.Keys);
重复:http://stackoverflow.com/questions/1276763/how-do-i-get-the-list-of-keys-in - 字典 – 2017-01-02 09:39:58