[英]LINQ: dictionary from string[]
I have to create a dictionary for use in a DropDownListFor based on absolute paths retrieved in a string[]. 我必须根据在string []中检索的绝对路径创建一个在DropDownListFor中使用的字典。 I want ot know if there's a way to have the key be just the folder name and the value be the full path?
我想知道是否有办法让密钥只是文件夹名称,值是完整路径?
Here's what I have so far: 这是我到目前为止所拥有的:
// read available content folders from FTP upload root
var path = HttpContext.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["ResearchArticleFTPUploadRoot"]);
var subfolders = System.IO.Directory.GetDirectories(path).ToDictionary(r => r, v => v);
ViewBag.BodyFolderChoices = new SelectList(subfolders, "Key", "Key");
I tried: 我试过了:
var subfolders = System.IO.Directory.GetDirectories(path).ToDictionary(r => r, v => new { v.Substring(v.LastIndexOf("/"), v.Length-v.LastIndexOf("/"))});
Thinking that grab after the last "/" in the path for the folder name as the Key... doesn't work... Ideas? 认为在文件夹名称的路径中的最后一个“/”之后抓住作为Key ...不起作用...想法?
using System.IO; // to avoid quoting the namespace everywhere it's used
var subfolderPaths = Directory.GetDirectories(path);
var dictionary = subfolderPath.ToDictionary(p => Path.GetFileName(p), p => p);
Note that GetFileName
in this context will return the folder name if you give it a full path to a folder. 请注意,如果为文件夹提供完整路径,则此上下文中的
GetFileName
将返回文件夹名称。
You could use DirectoryInfo
to do that: 您可以使用
DirectoryInfo
来执行此操作:
var subfolders = Directory
.GetDirectories(path)
.ToDictionary(r => r, v => new DirectoryInfo(v).Name);
EDIT 编辑
I am aware that the Key
-Properties will be the full path in this case. 我知道
Key
-Properties将是这种情况下的完整路径。 I did this to make sure you do not have to worry about duplicate keys when changing the operation to search for directories recursively: 我这样做是为了确保在更改操作以递归搜索目录时不必担心重复键:
var subfolders = Directory
.GetDirectories(path, "*", SearchOption.AllDirectories)
.ToDictionary(r => r, v => new DirectoryInfo(v).Name);
which could cause issues if a folder two folders contain a equally named sub folder. 如果文件夹两个文件夹包含同名的子文件夹,则可能导致问题。 If this is not a concern, you can switch the parameters of
ToDictionary
: 如果这不是问题,您可以切换
ToDictionary
的参数:
var subfolders = Directory
.GetDirectories(path)
.ToDictionary(v => new DirectoryInfo(v).Name, r => r);
坚持使用您的方法,以下工作:
var subfolders = System.IO.Directory.GetDirectories(path).ToDictionary(r => r, v => v.Substring(v.LastIndexOf("\\")+1, v.Length - v.LastIndexOf("\\")-1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.