user3925608
user3925608

Reputation: 13

How to convert string into Boolean flags in C# LinQ?

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();

Upvotes: 1

Views: 1593

Answers (2)

Saranga
Saranga

Reputation: 3228

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.

Upvotes: 1

metacubed
metacubed

Reputation: 7281

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.

Upvotes: 0

Related Questions