How to check if the file / element already exists in a & lt; String>?

advertisements

The variable fi (FileInfo[]) contain for example 10 files. I want to loop over the files and check if each one of them already exist in the List<string> AnimatedGifFiles if the first file in fi not exist in the List keep loop over and check for the second files and third and all the files in fi and then only continue.

The way I did it now if the first or second file not exist the program continue.

if (ToCreate == false)
{
    combined = Path.Combine(sf, fi[simtest].FullName);

    if (AnimatedGifFiles.Count == 0)
    {
        AnimatedGifFiles.Add(combined);
    }
    for (int i = 0; i < AnimatedGifFiles.Count; i++)
    {
        if (!AnimatedGifFiles[i].Contains(combined))
        {
            AnimatedGifFiles.Add(combined);//last_file);
        }
    }
    simtest += 1;
}


First, if you have a list, and want to loop through it, I would always recommend using foreach (string foo in foolist).

However, if you want to check if the string combined already exists in your list, you can simply check it with if (list.Contains(combined)) so looping through it should be unneccessary in your case.

This should work for you:

        if (ToCreate == false)
        {
            combined = Path.Combine(sf, fi[simtest].FullName);

            if (AnimatedGifFiles.Contains(combined) == false)
                AnimatedGifFiles.Add(combined);

            simtest ++;
        }