Angie
Angie

Reputation: 339

Parse a string combined of multiple enums' values

I have three enum types (enum1, enum2, enum3) whose values may contain _ char, and a string s of the pattern "enum1_enum2_enum3".

Now, I want to analyse the string s to get the three values of the enum types.

Is there an efficient way to do that?

Edit: An example:

enum enum1 {A_1 ,B_1, C_1} 
enum enum2 {A_2, B_2, C_2} 
enum enum3 {A_3, B_3, C_3}
string s = "A_1_B_2_C_3";

after parsing I should get:

enum1 part1 = enum1.A_1;
enum2 part2 = enum2.B_2;
enum3 part3 = enum3.C_3;

Upvotes: 1

Views: 680

Answers (1)

mrogal.ski
mrogal.ski

Reputation: 5920

Okay so the solution can be :

// your enumeration declaration ...
private enum enum1 { A_1, B_1, C_1 }
private enum enum2 { A_2, B_2, C_2 }
private enum enum3 { A_3, B_3, C_3 }

// string to process 
private static string s = "A_1_B_2_C_3";

// parsing result structure
private struct ParsingResult
{
    public Type enumType;
    public object enumValue;
}

After making these, create a placeholder for the results :

ParsingResult[] results = new ParsingResult[] {
    new ParsingResult() { enumType = typeof(enum1) },
    new ParsingResult() { enumType = typeof(enum2) },
    new ParsingResult() { enumType = typeof(enum3) }
};

Then iterate through these results to process string :

for (int i = 0; i < results.Length; i++)
{
    results[i].enumValue = Enum.GetNames(results[i].enumType).Select(value =>
    {
        int cIteration = 0;
        while (cIteration < s.Length && cIteration + value.Length <= s.Length)
        {
            string toProcess = s.Substring(cIteration, value.ToString().Length);
            cIteration += value.ToString().Length + 1;
            try
            {
                object valid = Enum.Parse(results[i].enumType, toProcess);
                return valid;
            }
            catch { }
        }
        return null;
    })
    .FirstOrDefault(v => v != null);
}

Of course it will return string value and not your enum but this you can make using :

results[i].enumValue = Enum.Parse(results[i].enumType, results[i].enumValue.ToString());

And I think it wont make you to much trouble implementing.

Later on using :

foreach (ParsingResult value in results)
{
    Console.WriteLine(value.enumValue);
}

Sample output should be :

A_1
B_2
C_3

EDIT :

I had to modify this a bit because it wasn't working as intended. Previously if you would have :

static string s = "W_4_A_1_B_2_C_3";

Output would be inaccurate and show values like B_2 and C_3 meaning it will omit the first enum. Now after simple edit it will return only valid values.

Upvotes: 1

Related Questions