question

osvbnet avatar image
0 Votes"
osvbnet asked karenpayneoregon answered

IEnumerable Items Count

Hey all,
The below code:

Dim MyFiles As System.Collections.Generic.IEnumerable(Of String)
MyFiles = Directory.EnumerateFiles(MyPath, "*.txt", SearchOption.AllDirectories)
For Each MyFile As String In MyFiles
...

How to get the number of files in MyFiles?
Since it is enumerating the collection before the whole collection is returned, not possible right?
I'm more comfortable with DirectoryInfo.GetFiles, and my files are not more than 5000, so much difference in efficiency?
Thanks

dotnet-visual-basic
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi

You ask 'how to get the number of files' - but I know that you know already - a simple

Dim count As Integer = MyFiles.Count

will get the number. The IEnumeration will be enumerated on demand to provide the result.

So, I suppose that is not what you are asking.

0 Votes 0 ·

1 Answer

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered

If in your code you are using GetEnumerator in tangent with MoveNext you can not get a count.

You could run the code below prior to your code to get a count.. In my test I asked for a file count in a folder with 125,000 files for only one file extension which comes back with 12,000 plus in a count which took 2.5 seconds. So for you to traverse 5,000 files will take no time.

 Imports System.IO
 Public Class Form1
     Public Async Function FileCount(sender As String, allowedExtensions() As String) As Task(Of Integer)
         Return Await Task.Run(
             Function()
                 Return Task.FromResult(
                     Directory.EnumerateFiles(
                         sender, 
                         "*.*", 
                         SearchOption.AllDirectories).Count(
                             Function (file)
                                 Return allowedExtensions.Contains(Path.GetExtension(file))
                             End Function))
             End Function)
     End Function
    
     Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
         Dim watch As Stopwatch = Stopwatch.StartNew()
         Dim count = Await FileCount(MyPath, { ".txt" })
         watch.Stop()
         Dim ts As TimeSpan = TimeSpan.FromMilliseconds(watch.Elapsed.TotalMilliseconds)
    
         MessageBox.Show($"File count: {count,-10}{ts.TotalSeconds}")
    
     End Sub
 End Class


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.