0

Consider the enum below:

public enum TestType
{
    Mil,
    IEEE
}

How can I parse the folowing strings to the above enum?

Military 888d Test in case of TestType.Mil Or IEEE 1394 in case of TestType.IEEE

My idea was to check if the first letters of string matches 'Mil' or 'IEEE' then I would set it as the enum I want, but the problemis there are other cases that should not be parsed!

Dumbo
  • 13,555
  • 54
  • 184
  • 288
  • 3
    Can you list the cases that should not be parsed? – Amith George Jul 16 '12 at 09:57
  • for example `Miltiary 833d Spiral` I dont want this tobe parsed – Dumbo Jul 16 '12 at 10:09
  • 1
    Why is this invalid? Because of 'Miltiary'? or '833d' or 'Spiral'? – Amith George Jul 16 '12 at 10:12
  • Generally the strings I have are in case of `military` are in 3 parts X Y Z , x is always military, y is always number+letter and Z is different type of tests – Dumbo Jul 16 '12 at 10:20
  • Simple enum parsing is not going to cut it. You need to test the string whether it matches any acceptable pattern. If it does, return the type associated with that pattern. Only you know the exhaustive list of acceptable patterns... – Amith George Jul 16 '12 at 10:30

6 Answers6

2

Already answred by me : How to set string in Enum C#?

Enum cannot be string but you can attach attribute and than you can read the value of enum as below....................

public enum TestType
{
      [Description("Military 888d Test")]
     Mil,
      [Description("IEEE 1394")]
     IEEE
 }



public static string GetEnumDescription(Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute),
        false);

    if (attributes != null &&
        attributes.Length > 0)
        return attributes[0].Description;
    else
        return value.ToString();
}

here is good article if you want to go through it : Associating Strings with enums in C#

Community
  • 1
  • 1
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • @TimSchmelter - its copy of my answer only i will put this at the top if you want ..not issues..thanks for poiting this – Pranay Rana Jul 16 '12 at 10:21
1

My understanding of your situation is that the string can come in any format. You could have strings like "Military 888d Test", "Mil 1234 Test", "Milit xyz SOmething"...

In such a scenario, a simple Enum.Parse is NOT going to help. You will need to decide for each value of the Enum, which combinations do you want to allow. Consider the code below...

public enum TestType
{
    Unknown,
    Mil,
    IEEE
}

class TestEnumParseRule
{
    public string[] AllowedPatterns { get; set; }
    public TestType Result { get; set; }
}


private static TestType GetEnumType(string test, List<TestEnumParseRule> rules)
{
    var result = TestType.Unknown;
    var any = rules.FirstOrDefault((x => x.AllowedPatterns.Any(y => System.Text.RegularExpressions.Regex.IsMatch(test, y))));
    if (any != null)
        result = any.Result;

    return result;
}


var objects = new List<TestEnumParseRule>
                  {
                      new TestEnumParseRule() {AllowedPatterns = new[] {"^Military \\d{3}\\w{1} [Test|Test2]+$"}, Result = TestType.Mil},
                      new TestEnumParseRule() {AllowedPatterns = new[] {"^IEEE \\d{3}\\w{1} [Test|Test2]+$"}, Result = TestType.IEEE}
                  };
var testString1 = "Military 888d Test";
var testString2 = "Miltiary 833d Spiral";

var result = GetEnumType(testString1, objects);
Console.WriteLine(result); // Mil

result = GetEnumType(testString2, objects);
Console.WriteLine(result); // Unknown

The important thing is populating that rules object with the relevant regular expressions or tests. How you get those values in to the array, really depends on you...

Amith George
  • 5,806
  • 2
  • 35
  • 53
0

try this var result = Enum.Parse(type, value);

burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
  • -1: This will not work as per the OP's specification (it would only parse `Mil` to `TestType.Mil`, but surely not `Military 888d Test`). – Christian.K Jul 16 '12 at 10:01
0

EDIT

use Enum.GetNames:

foreach (var value in Enum.GetNames(typeof(TestType))) 
{
    // compare strings here
    if(yourString.Contains(value))
    {
        // what you want to do
        ...
    }
}

If you using .NET4 or later you can use Enum.TryParse. and Enum.Parse is available for .NET2 and later.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Ria
  • 10,237
  • 3
  • 33
  • 60
0

Please try this way

    TestType testType;
    Enum.TryParse<TestType>("IEEE", out testType);

and it you want to compare string then

bool result = testType.ToString() == "IEEE";
HatSoft
  • 11,077
  • 3
  • 28
  • 43
0

Simple method will do it for you:

public TestType GetTestType(string testTypeName)
{
   switch(testTypeName)
   {
       case "Military 888d Test":
           return TestType.Mil;
       case "IEEE 1394":
           return TestType.IEEE;
       default:
           throw new ArgumentException("testTypeName");
   }
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459