LINQ: dictionary from string []

I need to create a dictionary to use in the DropDownListFor based on the absolute paths received in the [] line. I want to know if there is a way for the key to be just the folder name and the value to 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 capturing after the last "/" in the path for the folder name as a key ... doesn't work ... Ideas?

+3


source to share


3 answers


You can use DirectoryInfo

for this:

var subfolders = Directory
    .GetDirectories(path)
    .ToDictionary(r => r, v => new DirectoryInfo(v).Name);

      

EDIT

I know the Key

-Properties will be the full path in this case. I did this to make sure you don't have to worry about duplicate keys when changing the operation to find directories recursively:



var subfolders = Directory
    .GetDirectories(path, "*", SearchOption.AllDirectories)
    .ToDictionary(r => r, v => new DirectoryInfo(v).Name);

      

which can cause problems if a folder with two folders contains a similar subfolder. If this is not a concern, you can toggle the options ToDictionary

:

var subfolders = Directory
    .GetDirectories(path)
    .ToDictionary(v => new DirectoryInfo(v).Name, r => r);

      

+2


source


using System.IO; // to avoid quoting the namespace everywhere it 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 the full path to the folder.

+3


source


Using your method, follow these steps:

var subfolders = System.IO.Directory.GetDirectories(path).ToDictionary(r => r, v => v.Substring(v.LastIndexOf("\\")+1, v.Length - v.LastIndexOf("\\")-1));

      

0


source







All Articles