score:11

Accepted answer
static public bool IsLightFile(string fileName)
{
  //Use any with names returned from the enum.
   return Enum.GetNames(typeof(LightFiles)).Any(w => w == fileName);    
}

score:2

A little unsure precisely what you are asking, I can see three possibilities...

If you just want the file name to contain any of the enum strings, you could do:

    static public bool IsLightFile(string fileName)
    {
        foreach (var eVal in Enum.GetNames(typeof(LightFiles)))
        {
            if (fileName.Contains(eVal))
            {
                return true;
            }
        }

        return false;
    }

Or, if you want to see if it just ends with that extension, you could do:

    static public bool IsLightFile(string fileName)
    {
        foreach (var eVal in Enum.GetNames(typeof(LightFiles)))
        {
            if (Path.GetExtension(fileName).Equals(eVal))
            {
                return true;
            }
        }

        return false;
    }

Or, if you are saying that the filename must be equal to the enum value completely, you can do:

    static public bool IsLightFile(string fileName)
    {
        return Enum.IsDefined(typeof(LightFiles), fileName);
    }

Obviously, you'd want to null check, make string compare case-insensitive, etc as necessary.

score:1

public bool IsLightFile(string filename)
{
    return Enum.GetNames(typeof(LightFiles)).Contains(
        Path.GetExtension(filename).Remove(0, 1).ToUpper());
}

The only way LINQ plays a part in this is the Enumberable.Contains() extension method.

See also:

Enum.GetNames()
Path.GetExtension()
String.Remove()
String.ToUpper()

score:1

static public bool IsLightFile(string fileName)
    {
      var extension = Path.GetExtension(fileName).Remove(0, 1);
      return Enum.GetNames(typeof(LightFiles)).Any(enumVal => string.Compare(enumVal, extension, true) == 0);
    }

score:1

I don't see why you'd use LINQ here. To see if a string is a valid enum value, a slightly more natural solution than looping over Enum.GetNames's results, whether explicitly or implicitly using LINQ, would be Enum.TryParse.

string fileExtension = Path.GetExtension(fileName);
if (fileExtension.StartsWith("."))
    fileExtension = fileExtension.Substring(1);
LightFiles lightFile;
return Enum.TryParse(fileExtension, true, out lightFile);

Note: the alternative Enum.IsDefined is always case sensitive, while file extensions are usually treated as case insensitive.


Related Articles