I have a user class that has a LIST of roles, which are gotten from the database e.g. SUPERADMIN, COMPANY, ACCOUNTS, USERS etc
Since the SUPERADMIN user can only be added by a similar user, I want to add a security check to ensure when a user is created, it cannot be added by another user.
PROBLEM i know the list view in my C# view page, is 10, so if I hard code the value, I can easily get back the index
Here is my code
OPTION 1 - HARD CODE THE INDEX VALUE
if (user.UserRoles[10].RoleName.Any(c => c.Equals("SUPERADMIN")))
{
// Add logic here
}
OPTION 2 - LOOP THROUGH ALL VALUES
for(int i = 0; i < user.UserRoles.Count(); i )
{
if (user.UserRoles[i].RoleName.Any(c => c.Equals("SUPERADMIN")))
{
// Add logic here
}
}
I am guessing there is a simple way to do it in a lambda expression ? or something else ?
many thanks
CodePudding user response:
Assuming UserRoles
is an object array where the object contains a RoleName
property of type string
. Is the following what you are after?
if ( user.UserRoles.Any( r => r.RoleName.Equals("SUPERADMIN") ) ) { ... }