Landi
Landi

Reputation: 661

Add enums to a list according to the value received back from database

How will I add enums to a list according to the value I get back from the database, If the value is 1 then add to the list else don't.

This is what I have more or less:

Permissions = new List<Permission>()
{
    ((int)data[0]["AllowOverride"] == 1 ? Permission.AllowOverride : "I do not have an else")
    ((int)data[0]["AllowAttachment"] == 1 ? Permission.AllowAttachment: "I do not have an else")
},

EDIT: I am constructing this list as part of an object initializer.

Upvotes: 3

Views: 66

Answers (2)

FarligOpptreden
FarligOpptreden

Reputation: 5043

You can try setting the property based on the result of a lambda function, which negates the necessity of a separate function to construct the permissions. You can try something along the lines of:

Permissions = 
    new Func<DataRow, List<Permission>>(permissionData =>
    {
        List<Permission> permissions = new List<Permission>();
        // do all your if checks here to add the necessary permissions to the list
        return permissions;
    })(data[0])

EDIT: I just changed some variable names so it would actually compile without conflicting with your "data" variable already in use.

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174309

No need for the conditional operator here, you simply use if:

Permissions = new List<Permission>();

if(((int)data[0]["AllowOverride"]) == 1)
    Permissions.Add(Permission.AllowOverride);

if(((int)data[0]["AllowAttachment"]) == 1)
    Permissions.Add(Permission.AllowAttachment);

Upvotes: 3

Related Questions