lundi 22 janvier 2018

switch() statement with string.contains() as parameter

I'm somewhat new to C# and I'm trying to create a switch method that returns an ID (int) corresponding to the given filename.

For example:

var fileName = "file-example_MAP_COPY.xml";
var fileTypeId = GetFileTypeId(fileName); // Returns 3310

With the GetFileTypeId method looking something like this:

private GetFileTypeId(string fileName)
{
    switch(string.Contains(fileName))
    {
        case ".xsd":
            return 3010;
        case "_Gui.xml":
            return 3120;
        case ".xml":
            return 3300;
        case "_MAP_COPY.xml":
            return 3310;
        ...
    }
}

I cannot trim the actual filename off and only keep the extension since the filename could contain underscores. A file with the name "example_1_MAP_COPY.xml" would be trimmed to "_1_MAP_COPY.xml" if trimmed at first underscore, resulting in a faulty file extension.

An if statement would work here, but since I have 18 different cases I'd like to find another solution than to write 18 if statements.

Is there some way I can go about to do this, either with a switch statement or a dictionary perhaps?

Aucun commentaire:

Enregistrer un commentaire