Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: dictionary from string[]

I have to create a dictionary for use in a DropDownListFor based on absolute paths retrieved in a string[]. 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?

like image 459
Beau D'Amore Avatar asked Nov 26 '25 17:11

Beau D'Amore


1 Answers

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.

like image 77
Gary McGill Avatar answered Nov 28 '25 15:11

Gary McGill