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?

JKennedy
  • 18,150
  • 17
  • 114
  • 198

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
  • 607,720
  • 39
  • 448
  • 563
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();
     }
}
JKennedy
  • 18,150
  • 17
  • 114
  • 198