Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if a string is not equal to multiple different strings?

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?

like image 430
Chaddeus Avatar asked Oct 10 '11 08:10

Chaddeus


2 Answers

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.

like image 141
Jon Skeet Avatar answered Oct 06 '22 02:10

Jon Skeet


You can use !Regex.IsMatch(extension, "^\.(jpg|jpeg|gif|png|bmp)$")

but internally somehow it will still loop

like image 31
fixagon Avatar answered Oct 06 '22 00:10

fixagon