0

so I have some strings in a list

Folder1\File.png
Folder1\File2.png
File3.png
File4.png

and I would like to group these on a split('\\')[0]; for example

foreach (var group in files.GroupBy(x => //mysplit))
{
   if (group.Count() > 1)
   {
      // this is a folder and its files are: group
   }
   else
   {
      //group is an individual file
   }
}

but I'm not sure how to group the files by this split?

User1
  • 17,202
  • 13
  • 104
  • 183
  • If these are valid paths, you may want to use .NET built-in checks. http://stackoverflow.com/questions/439447/net-how-to-check-if-path-is-a-file-and-not-a-directory – Victor Zakharov Mar 19 '15 at 11:22
  • Theyre Azure paths, I am building my own Azure explorer – User1 Mar 19 '15 at 11:24

2 Answers2

0

I would just group items that Contains() a backslash:

var lst1 = new string[] {"Folder1\\File.png", "Folder1\\File2.png" , "File3.png", "File4.png" };
var grps = lst1.GroupBy(x => x.Contains(@"\"));
foreach (var g in grps)
{
    if (g.Key) // we have a path with directory
        Console.WriteLine(String.Join("\r\n", g.ToList()));
    else // we have an individual file
         Console.WriteLine(String.Join("\r\n", g.ToList()));
}
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
0

So my solution was:

foreach (var groupedFiles in files.GroupBy(s => s.Split('\\')[0]))
{
     if (Path.GetExtension(groupedFiles.Key) == string.Empty)
     {
          //this is a folder
          var folder = groupedFiles.Key;
          var folderFiles = groupedFiles.ToList();
     }
     else
     {
          //this is a file
          var file = groupedFiles.First();
     }
}
User1
  • 17,202
  • 13
  • 104
  • 183