Pete Pete - 1 month ago 4
C# Question

Iterate through two directories

I am looking to iterate through two directories. I am aware of options available to iterate through each directory and storing the list of all the details it found within it in a list. I was wondering if there is a better way of achieving this in C# without iterating through each directory and storing the details in a separate list.The requirement is while iterating through one of the directory for all its contents, I want to compare each item in that directory to the one in the second directory

Answer

I was wondering if there is a better way of achieving this in C# without iterating through each directory and storing the details in a separate list.

Use EnumerateFiles on both directories, zip-join them, and then run the join through a foreach loop.

var firstFiles = Directory.EnumerateFiles(...);
var secondFiles = Directory.EnumerateFiles(...);
var joined = firstFiles.Zip(secondFiles, 
  (first, second) => new { First = first, Second = second });
foreach(var pair in joined)
{
   // now do something with pair.First and pair.Second
}