You need to check the existence of the file by the paths from List dino, if there are nonexistent files, then delete these paths and transfer this new data to the dino sheet or to the new sheet again so that you can use these paths later in the cycles.

static void Main(string[] args) { string[] basePaths = { "folders\\text.txt", "folders\\text.txt", "folders\\text.txt" }; List<string> dino = new List<string>(basePaths); 

I try to do all this through a cycle, but in the cycle you cannot change the collection data

 foreach (string dino2 in dino) { if (!(File.Exists(dino2))) dino.Remove(dino2); } 

I looked through many examples in the documentation and on the Internet, found nothing similar, maybe I just didn’t stumble upon the right UPD option: I tried the for loop, the program stops

 List<string> dino = new List<string>(basePaths); for (int i = dino.Count - 1; i >= 0; i--) { if (!(File.Exists(dino[i]))) { dino.Remove(dino[i]); } Console.WriteLine(dino[i]); } 
  • @Andrey NOP, debugging at the output from the console stopped, already corrected my mistake was - Bortman

1 answer 1

Here are some solutions:

The classic way, in this case, is to use the for loop, but, at the same time, in order that the deletion of elements does not affect their search, you should go to the end of the list:

 for (int i = dino.Count - 1; i >= 0; i--) if (!File.Exists(dino[i])) dino.RemoveAt(i); 

The next way is to use the tools built into the List class for mass deletion of elements that satisfy a certain condition:

 dino.RemoveAll(e => !File.Exists(e)); 

And, finally, a more modern way, with hints of functional programming, but, in this case, most likely, not the most effective - use Linq. Keep in mind, Linq does not change the collection (sequence), it creates new ones, so you have to explicitly overwrite the link to the collection:

 dino = dino.Where(e => File.Exists(e)).ToList(); 
  • Just edited the question with the addition of a for loop with a brute force from the end) I checked by your example, now the collection has changed) - Bortman
  • thanks for the help! - Bortman