IEnumerable Items Count

OSVBNET 1,386 Reputation points
2022-05-16T23:59:03.627+00:00

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

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,561 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,026 Reputation points
    2022-05-17T19:37:08.417+00:00

    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
    
    0 comments No comments