C# – way to check if a string is not equal to multiple different strings

cnetstringstring-comparisonvalidation

I want to validate a file uploader, by file extension. If the file extension is not equal to .jpg, .jpeg, .gif, .png, .bmp then throw validation error.

Is there a way to do this without looping through each type?

Best Answer

Just build a collection - if it's small, just about any collection will do:

// Build the collection once (you may want a static readonly variable, for
// example).
List<string> list = new List<string> { ".jpg", ".jpeg", ".gif", ".bmp", ... };

// Later
if (list.Contains(extension))
{
    ...
}

That does loop over all the values of course - but for small collections, that shouldn't be too expensive. For a large collection of strings you'd want to use something like HashSet<string> instead, which would provide a more efficient lookup.