如何从数组和列表中制作带有键的字典?
我有这两个集合:
List<string> files =
Directory.GetFiles(FilePath).ToList().Select(file => new FileInfo(file).Name).ToList();
string[] dirs = Directory.GetDirectories(FilePath);
但是,我想将这两个集合添加到一个空字典中,因此我有一个包含路径和文件的大字典。我不确定的是,如何/在哪里指定密钥?
对于文件,我希望文件名作为键,对于目录,我希望最后一个目录(例如 a/b/c 中的 c)作为键。我知道如何使用 FileInfo/DirectoryInfo 类获取此信息,但不确定如何将其包含在从上面创建字典中?
我正在使用 .NET V3.5 并且 LINQ 很好。
谢谢
I have these two collections:
List<string> files =
Directory.GetFiles(FilePath).ToList().Select(file => new FileInfo(file).Name).ToList();
string[] dirs = Directory.GetDirectories(FilePath);
However, I'd like to add both of these to an empty dictionary, so I have a large dictionary with paths and files. The thing I am not sure of, how/where do I specify the keys?
For files, I want the filename as the key, and for the directories, I want the last directory (e.g. c in a/b/c) to be the key. I know how to get this information with FileInfo/DirectoryInfo classes, but not sure how to include this in creating a dictionary from the above?
I'm using .NET V3.5 and LINQ is fine.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于文件,您可以
对目录执行以下操作:
For files, you can do
for directories,
如果您已经拥有所需的信息,并且知道如何正确配对。您只需使用此语句将其添加到字典中即可。
除非我不理解你?您想问如何添加它们吗?或者如何正确地将文件与目录配对?
If you already have the information you need, and you know how to pair it up properly. You just use this statement to add it to the dictionary.
Unless I'm not understanding you? Are you asking how to add them? Or how to pair the file with the directory properly?
到目前为止,我最喜欢 Bala R 的 LINQ 答案(并且他得到了我的支持),但值得一提的是,在一般情况下,当您想要组合
List< /code> 和一个
string[]
到一个Dictionary
中,你总是可以使用基本的for
循环:它可能有点无聊,但它适用于任何一对
IEnumerable
集合。So far I like Bala R's LINQ answer best (and he's got my upvote), but it's worth mentioning that in a general case, when you want to combine a
List<string>
and astring[]
into aDictionary<string, string>
, you can always go with a basicfor
loop:It might be a little boring, but it'll work for any pair of
IEnumerable<T>
collections.