1

I have declared the Boolean flags as below.

[Flags]
    public enum StudentStatus
    {
        True = 1,
        False = 2

    }

I'm getting the value through the DataValues collections in the below line and I want to assign it into the below property.

var student= new Student();

student.Status= StudentInfo.Data.DataValues
                .Where(m => m.FieldName.Equals("Status"))
                .Select(m => m.StatusValue).SingleOrDefault();

2 Answers 2

1

Since you are using .Net Framework 4 you can use Enum.TryParse method.

var student= new Student();

string status = StudentInfo.Data.DataValues
                                 .Where(m => m.FieldName.Equals("Status"))
                                 .Select(m => m.StatusValue).SingleOrDefault();
StudentStatus studentStatus;
Enum.TryParse(status, out studentStatus);

student.Status = studentStatus;

If the parse operation fails, result contains the default value of the StudentStatus.

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

Comments

0

First of all, that enum is not well suited for being a [Flags] enum. [Flags] is only used if many different values can be active at one time. It should be declared as:

// Removed [Flags] - not appropriate here.
public enum StudentStatus
{
    True = 1,
    False = 2
}

In any case, you can use Enum.Parse to parse the string back into an enum. Like so:

string statusString = StudentInfo.Data.DataValues
                                 .Where(m => m.FieldName.Equals("Status"))
                                 .Select(m => m.StatusValue).SingleOrDefault();

student.Status = (StudentStatus) Enum.Parse(typeof(StudentStatus), statusString);

This will work for both [Flags] and normal enums.

1 Comment

Thanks a lot for your quick response. There is a method which required the flags to be set. the above example is to understand for the conversion in such scenarios. So is your code works including the Flags??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.