开发者

Difficulty in filling list while comparing arrays

In the following I want to use GetUsersRole but having difficulty with the part shown. I want to compare the Roles values with usersRole, and if Role==usersRole, then UserRole = true, else false.

basically I want to have somehing like this as my result :

user1: true

user2:false

user 3: false

user4: true

depending on usersRole

Class Role

public enum Role
{            开发者_运维问答                                
    User1 = 1,
    User2= 2,
    User3= 3, 
    User4= 4
}

I am having a class

private class UserRoleModel
{
    public string Role { get; set; }
    public bool UserRole { get; set; }
}

and a method

public Role[] UserRoles { get; set; }  
private static UserRoleModel[] GetUsersRole(Role[]usersRole)
{
    List<UserRoleModel> rolesList = new List<UserRoleModel>();
    string[] Roles;
    Roles = new string[] { Role.user1.ToString(), Role.User2.ToString(), 
              Role.user3.ToString(), Role.user4.ToString() };
    foreach (var item in Roles)
    {
        rolesList.Add(new UserRoleModel
        {
            Role = item,
            *UserRole = usersRole.Contains(item)* ////difficulty here
        });
    }
    return rolesList.ToArray();
}


You are running into this problem because you are turning the Role values into strings when you don’t actually need a string. Move the ToString() to where you actually need it:

public Role[] UserRoles { get; set; }  
private static UserRoleModel[] GetUsersRole(Role[]usersRole)
{
    List<UserRoleModel> rolesList = new List<UserRoleModel>();

    Role[] roles = (Role[]) Enum.GetValues(typeof(Role));

    // or if you need the specific three values like in your example:
    // Role[] roles = new Role[] { Role.User1, Role.User2, Role.User3, Role.User4 };

    foreach (var role in roles)
    {
        rolesList.Add(new UserRoleModel
        {
            Role = role.ToString(),
            UserRole = usersRole.Contains(role)
        });
    }
    return rolesList.ToArray();
}


Check last Update for correct answer

I dont understand what you are trying to do. But from the code shown in your question, i can see that u are Calling Contains method

userRole.Contains(item);

and i am assuming that you are trying to find the item in array of Roles But in the context the argument you took userRole is not an Array. To correct instead of :

private static UserRoleModel[] GetUsersRole(Role usersRole)

you should write:

private static UserRoleModel[] GetUsersRole(Role[] usersRole)

Update

Ok i get it.. The problem is that in Contains methofd you are searching by passing a String where as the array contains values of Type Role.

So the question is how to find a Enum Instance in an Array of Enum Instances from a string representation of Enum Instance

Normally you can only search by the Type of the Items in the Array but here you have a string Representation so something like this can be done:

create a function:

public Role GetRole(string rolestring)
{
     Role result; 
     foreach(string rolename in Enum.GetNames(typeof(Role)))
     {
       if(rolename == rolestring)
       {
           try 
           {
             result = (Role) Enum.Parse(typeof(Role), rolename); 
           }
           catch(ArgumentException e)
           {
                 //Most unlikely we ever enter this catch s we know for sure we have role
                 //Process if role not found
                 throw;
           }
       }
     }
     return result;
}

then in your code

UserRole = usersRole.Contains(GetRole(item));


Update

There is no Contains Method in Type Array

Ok i get it.. The problem is Contains method as there is no such method as Contains for Type Arrays instead its for Type List<T>

For arrays we have Exists which takes a Predicate as an argument to search and return bool.

Use it like as follows:

//just to be sure correct value is captured everytime
string copy = item;
//Predicate is in System.Predicate<T>
Predicate<string> predicate = itemtocheck => {   
       itemtocheck == copy;
   };
UserRole = Array.Exists(Enum.GetNames(typeof(Role)), predicate);


My First update was correct but then i didn't notices that array dont have method Contains. Check my last update correct answer Hope it helps


*UserRole = usersRole.Contains(item)* ////difficulty here

Change this to:

UserRole = false;
foreach(Role r in usersRole)
{
    if(r == item)
    {
        UserRole = true;
        break;
    }
}


Between this and your previous question, I think I can figure out what you are trying to do.

First off, if your users can be in multiple roles, you'll want your roles enumeration to be decorated with the [Flags] attribute. I'm assuming this is what you want since you're using check boxes and not a radio selector.

Next, to dynamically get the names for the Roles, you'll want to use something more like [Enum.GetNames(enum)]. If you'd like something better for a description than the name of the value in the enum, you can google for a GetDescription function pretty easily and then apply a [Description(...)] attribute to each one.

You will also want to write an enum.HasFlag(MyEnum.ValueToCheckAgainst) extension function (or use the one built in .NET 4.0) to determine if the checkbox is checked or not.

Also, @Shekhar_Pro's answer is also useful because you'll want your function to only take a single Role, not an array of them to generate the list of UserRoleModels. You will then call this function for each user you want to display.

And the last part, turning those check boxes back into a Role value, you'll have to do that manually. Write a function which takes an array of Role values and AND's them all together (after you make it a legitimate flags enum). Then just return the result. If you want something more "elegant" than that, you'll probably just want to make that function an extension on whatever you think should output those values (like your view model).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜