code_junkie

Check if an enum has a field that equals a string

Nov 12th, 2011
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. public enum FileExtentions {
  2. mp3,
  3. mpeg
  4. }
  5.  
  6. FileExtensions.Any(e=>e.ToString().Equals(file.Extension));
  7.  
  8. Enum.GetNames(typeof(FileExtensions)).Any(f=>f.Equals("."+file.Extension))
  9.  
  10. public static bool HasExtension(this FileInfo file)
  11. {
  12. var ext = file.Extension.StartsWith(".") ? file.Extension.Substring(1)
  13. : file.Extension;
  14.  
  15. return Enum.GetNames(typeof(FileExtensions))
  16. .Any(f => f.Equals(ext));
  17. }
  18.  
  19. bool hasExtension = file.HasExtension();
  20.  
  21. string extension = Enum.GetName(typeof(FileExtensions), FileExtensions.mp3);
  22.  
  23. if (extension == file.Extension)
  24. // do something here
  25.  
  26. bool result = Enum.GetNames(typeof(FileExtensions)).Contains("mp3");
  27.  
  28. Enum.IsDefined(typeof(FileExtension), file.Extension.Substring(1).ToLower())
  29.  
  30. IEnumerable<string> GetNames(this Type t) {
  31. if (!t.IsEnum) throw new ArgumentException();
  32.  
  33. return Enum.GetNames(t);
  34. }
  35.  
  36. typeof(FileExtensions).GetNames().Any(e=>e.ToString().Equals(file.Extension));
  37.  
  38. bool IsDefined(this Type t, string name) {
  39. if (!t.IsEnum) throw new ArgumentException();
  40.  
  41. return Enum.IsDefined(t, name);
  42. }
  43.  
  44. typeof(FileExtension).IsDefined(file.Extension);
Add Comment
Please, Sign In to add comment