Disadvantages of using ToList().ForEach to iterate through an array/IEnumberable instead of a normal foreach loop

I've recently started using the ToList().ForEach method to iterate through arrays or IEnumberables(eg the returns of .Select or .Where, etc.) instead of initializing the arrays and then interating through the values with a normal foreach loop. It seems a little bit easier to me and allows me to code a little bit quicker. Some examples

Normal foreach

 private bool Example(string path, string desiredErrorMessage) { DirectoryInfo dirInfo = new DirectoryInfo(path); bool containsError = false; var errorFiles = dirInfo.GetFiles() .Select(x=>x.Name.Contains("error")); foreach(var file in errorFiles) { string[] errorLines = File.ReadAllLines(file); foreach(var line in errorLines) { if(line.Contains(desiredErrorMessage)) { containsError=true; } } } return containsError; } 

ToList.ForEach example of same code:

private bool Example(string path, string desiredErrorMessage) { DirectoryInfo dirInfo = new DirectoryInfo(path); bool containsError = false; dirInfo.GetFiles() .Select(x=>x.Name.Contains"error") .ToList() .ForEach(thisFile=> { File.ReadAllLines(thisFile) .ToList() .ForEach(line => { if(lines.Contains(defaultErrorMessage)) { containsError=true; } }); })}; return containsError; } 

I'm just wondering if there are any disadvantages to using the second method memory allocation/efficiency wise. I know a list is basically just an array with a wrapper around it that adds some functionality so I figure maybe a list takes a little more memory than an array of the same variables. Are there any potential downsides to my method I am not considering?

Edit: Also if anyone has suggestions on a better way to implement this method or a similar one, I'd love to hear it. I'm fairly new in software development, my degree is in Biomedical Engineering and the curriculum had very little formal coding classes. Basically just MATLAB and that's it. Always looking for ways to get better at coding/development.

by wataf via /r/csharp

Leave a Reply