0

I'd like to get files from a specific folder in order to display them in a carousel, so I'm using :

string[] files = Directory.GetFiles("path/to/my/folder")

However, the files are ordered by their name in files[]

In my page (a strongly-typed view), my Model contains a dozen of properties, including a List<FileModel> filesToDisplay which is populated by pictures to display. A FileModel is a custom model, which contains the name, the size, a boolean IsMain and other some pictures properties.

On the other hand, the filesToDisplay list is populated from my database, in which I'm going to search which pictures I have to display. All the pictures are in the same directory, but I can't always display ALL the pictures of this directory ; this is why I'm searching to the DB which ones to display.

My goal is to display files in my carousel :

  • With the picture where IsMain is true in first position. There is always one and only one picture where IsMain is true
  • Then, as a second picture, the first picture where IsMain is false from filesToDisplay
  • Then as a third picute, the seconde picture where IsMain is false from filesToDisplay

etc...
Of course, the order in filesToDisplay can be (and is almost always) different from files[]

So, I'd like to do something like this :

files.OrderBy(filesToDisplay.IsMain).ThenBy(filesToDisplay(x => !x.IsMain))

which is of course impossible.

How can I express it in "correct" C# ? Thanks for your help !

(Yes, I've already seen this SO question, or this one which are very close to mine, but I was unable to adapt the answer to my problem). Sorry for newbie question.

Community
  • 1
  • 1
user2687153
  • 427
  • 5
  • 24

1 Answers1

1

My understanding is that you want the sorted files to be in the same order as the files to display, except that you want IsMain to be first. I think this code should satisfy that requirement;

       string[] files = Directory.GetFiles("path/to/my/folder");

        var sortedFiles = (from o in filesToDisplay
                              join i in files
                              on o.Name equals Path.GetFileName(i)
                              orderby o.IsMain descending 
                              select i).ToArray();

This will order the sorted files by IsMain first, of which there is always one so that goes to the first element in the array then the rest of the ordering is via the LINQ join where the sortedFiles sequence uses the existing order from the filesToDisplay sequence.

(This assumes that FileModel holds the FileName and each entry in string[] files is a filePath containing the file names.
eg. FileModel FileName: Picture1.jpg, files[0]: C:/RandomPath/Images/Picture1.jpg as you need a value to link up each file in files[] to each FileModel in filesToDisplay.)

user2687153
  • 427
  • 5
  • 24
MaxJ
  • 1,945
  • 2
  • 12
  • 19