Often when comparing characters with a list of characters, that list does not consist of consts.
It if were, you could make a switch statement:
switch (item) { case '/': case '\\': case ';': addSeparator(separatorsUsed, item); break; }
But reality is that you cannot do things like this:
switch (item) { case Path.AltDirectorySeparatorChar: // Error: A constant value is expected case Path.DirectorySeparatorChar: case Path.PathSeparator: addSeparator(separatorsUsed, item); break; }
However, you can perform a small trick and use LINQ to write some pretty elegant code based on Contains.
char[] pathSeparators = { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar, Path.PathSeparator }; // LINQ: http://stackoverflow.com/questions/1818611/how-to-check-if-a-char-in-a-char-array/1818635#1818635 if (pathSeparators.Contains(item)) addSeparator(separatorsUsed, item);
The LINQ logic has the logic backwards (you can think of it like “item in pathSeparators”, but it is far easier to read than this:
if ((item == Path.AltDirectorySeparatorChar) || (item == Path.DirectorySeparatorChar) || (item == Path.PathSeparator)) addSeparator(separatoseparatorsUsedrsInUse, item);
Full source of a demo application: Read the rest of this entry »