Search code examples
c#linqfilefileinfo

Getting x number of files after a certain file


I have a folder with Jpeg-files which i want too pull 3-4 at a time after sorting them for when they were lastly written. The thing is that i want to specify a start location (by file name) and only pull from there.

Example of a directory with pictures,

  • a.jpg
  • b.jpg
  • c.jpg
  • d.jpg
  • e.jpg
  • f.jpg
  • etc until j.jpg

Now i want to get 3 files starting from b.jpg, meaning that i want to order the files, search for a specific file (in this case b.jpg) and then take the following 3 files that comes after b.jpg (c.jpg, d.jpg and e.jpg in the example above).

How can i find the index of b.jpg using LINQ or better yet, get the 3 files in the same query?

index of file/the files directly = Directory.GetFiles(pathToFiles, "*.jpg").Select(x => new FileInfo(x)).OrderByDescending(x => x.LastWriteTime)... ?

Solution

  • You'll want to look into the SkipWhile extension method, the Skip extension method, and then the Take extension method.

    Additionally, utilize the Directory.EnumerateFiles instead.


    var files = Directory.EnumerateFiles(pathToFiles, "*.jpg")
                         .Select(x => new FileInfo(x))
                         .OrderByDescending(x => x.LastWriteTime)
                         .SkipWhile(x => !String.Equals(x.Name, "b.jpg")
                         .Skip(1)
                         .Take(3);
    

    Basically, once you have your ordered sequence, skip everything until you reach the "b.jpg" file, then skip that one file, then take the next three.


    Update: Now that I think about it, the EnumerateFiles will help a bit, but not entirely since you negate deferred execution with ordering. But, it'll still be a slight advantage (I think).