This project is read-only.
1
Vote

DirectoryInfoExtensions.GetFiles is not lazy

description

The DirectoryInfoExtensions.GetFiles method builds a List<T> containing every matching file. If you're only looking for the first few matching files, this wastes time and memory.
 
You can use SelectMany to make the method return a lazily-evaluated sequence:
 
public static IEnumerable<FileInfo> GetFiles(this DirectoryInfo directoryInfo, IEnumerable<string> searchPatterns)
{
if (null == directoryInfo) throw new ArgumentNullException("directoryInfo");
if (null == searchPatterns) throw new ArgumentNullException("searchPatterns");
if (!directoryInfo.Exists) return Enumerable.Empty<FileInfo>();

return searchPatterns
    .Distinct(StringComparer.OrdinalIgnoreCase) // Don't search for the same pattern twice
    .Where(pattern => null != pattern) // Avoid the "ArgumentNullException" for null patterns
    .SelectMany<string, FileInfo>(directoryInfo.GetFiles);
}
 
If you're compiling with VS2010, you can also omit the type parameters on the SelectMany call, as the compiler will infer them.

comments