-5

I have a simple method:

internal void run()
{
    foreach (string file in Directory.GetFiles(Path).ToList()
        .Where(x => DateTime.Today.Subtract(File.GetCreationTime(x)).Days > NumberOfDays))
    {
        File.Delete(file);
    }
}

Is it possible to get rid of the foreach statement?

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
Franco Pettigrosso
  • 4,056
  • 2
  • 20
  • 32
  • 1
    This is kind of question for code review: https://codereview.stackexchange.com/ – Markiian Benovskyi Sep 22 '17 at 14:52
  • To do what? If you have a collection to iterate over, then some variant of a loop is needed. To my knowledge, there is no bulk file delete in .NET – DiskJunky Sep 22 '17 at 14:52
  • Why should you do that? The code is quite easy to understand, which afaik is the best quality-measurement. What don´t you like about that code? Or is there anything that doesn´t work as expected? – MakePeaceGreatAgain Sep 22 '17 at 14:53
  • btw, there is an awesome method `ForEach()` – Markiian Benovskyi Sep 22 '17 at 14:54
  • @MarkBenovsky Where is `List.ForEach`any different to a classic `foreach`? Furthermore the former assumes you even *have* an instance of `List`. – MakePeaceGreatAgain Sep 22 '17 at 14:54
  • 1
    While it may be a dupe of the one I linked to, and it gives an answer, you should be aware of the fact that not everyone likes to see actions being performed in such a way - read all the answers, [particularly this one](https://stackoverflow.com/a/529197/791010). – James Thorpe Sep 22 '17 at 14:55
  • @JamesThorpe good explanation, I'm just to keep it the way the method is. More just out of curiosity. – Franco Pettigrosso Sep 22 '17 at 14:58
  • 1
    Be aware that every "simplification" you introduce (e.g. by using any Linq-method) only *hides* the loop. If you have some operation to be done on all items of a collection, of course you should *iterate* that collection. So all you gain when using another approach is to hide complexity. – MakePeaceGreatAgain Sep 22 '17 at 15:00
  • 1
    Another thing is that you can omit the call to `ToList()` after `GetFiles`, as the loop will iterate the files anyway. – MakePeaceGreatAgain Sep 22 '17 at 15:01

1 Answers1

-2
Directory.GetFiles(Path).ToList()
    .Where(x => DateTime.Today.Subtract(File.GetCreationTime(x)).Days > NumberOfDays)
    .ForEach(File.Delete);
Cronan
  • 183
  • 1
  • 10