本文介绍了比较数组时填充列表困难的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面,我想使用GetUsersRole,但是在显示的部分上有困难。我想将Roles值与usersRole进行比较,如果Role == usersRole,则UserRole = true,否则为false。
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
user1: true
user2:false
user2:false
用户3:错误
user4:正确
取决于用户角色
类角色
public enum Role
{
User1 = 1,
User2= 2,
User3= 3,
User4= 4
}
我正在上课
private class UserRoleModel
{
public string Role { get; set; }
public bool UserRole { get; set; }
}
和一种方法
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();
}
推荐答案
您正在遇到此问题因为您实际上不需要字符串时将 Role
值转换为字符串。将 ToString()
移至实际需要的位置:
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();
}
这篇关于比较数组时填充列表困难的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!