Home > Blockchain >  vb.net - Pick 1000 random files from a folder
vb.net - Pick 1000 random files from a folder

Time:03-05

I have a folder that has a many files in it. somewhat between 1000 and 15000.

I would need to randomly pick 1000 files from this folder and copy it over to another folder. I know how to get a single random file from a folder by inserting the list of files in an array and then selecting one randomly, but dont know how to get many while avoiding to select the same file twice.

If for example I have 1001 file in my folder, it will have no trouble getting the fist few, but then towards the end, it is very likely to pick a file that has already been copied over and it would take many tries to find for example the last file just by luck...

my first idea was to divide the number of files by 1000. so for example 1500/1000 = 1.5. and then create a random integer between 0 and 1.5. this would return 1. then do the next rand between nth image and nth image * 1.5.

if the folder hast 15000 files, it would pick the first file randomly between 1 and 15, and then between 6 and 30 and so on..

but there must be a smarter solution for this..

any help appreciated

CodePudding user response:

You can order them randomly:

Dim allFiles = Directory.EnumerateFiles("path")
Dim rnd As New Random()
Dim random1000 = From f In allfiles
                 Order By rnd.Next()
                 Select f
                 Take 1000
Dim list = random1000.ToList()

This is using System.Linq

CodePudding user response:

Using indices into the list of files

Private Shared prng As New Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim ListOfiles() As String = IO.Directory.GetFiles(BasePath)
    Dim indices As IEnumerable(Of Integer)
    indices = Enumerable.Range(0, ListOfiles.Length).OrderBy(Function() prng.Next).Take(1000)

    For Each idx As Integer In indices
        Dim fn As String = ListOfiles(idx)
        Stop
    Next
End Sub
  • Related