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!

5
  • 3
    Can you list the cases that should not be parsed? Commented Jul 16, 2012 at 9:57
  • for example Miltiary 833d Spiral I dont want this tobe parsed Commented Jul 16, 2012 at 10:09
  • 1
    Why is this invalid? Because of 'Miltiary'? or '833d' or 'Spiral'? Commented Jul 16, 2012 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 Commented Jul 16, 2012 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... Commented Jul 16, 2012 at 10:30

6 Answers 6

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#

Sign up to request clarification or add additional context in comments.

1 Comment

@TimSchmelter - its copy of my answer only i will put this at the top if you want ..not issues..thanks for poiting this
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...

Comments

0

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

1 Comment

-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).
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";

Comments

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");
   }
}

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.