1

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

Adesuwa
  • 25
  • 4
  • Assuming `RoleName` is a string, `RoleName.Any(c => c.Equals("SUPERADMIN"))` does not make sense - it will compare each character of the role name to the string "SUPERADMIN" which will of course yield false. You probably mean `RoleName.Equals("SUPERADMIN")` – Klaus Gütter Aug 30 '22 at 11:21
  • My advice, since is a `List` is to replace `.Any` with `.Exist` More info at https://stackoverflow.com/questions/879391/linq-any-vs-exists-whats-the-difference – Camadas Aug 30 '22 at 12:08

1 Answers1

0

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") ) ) { ... }

Terry
  • 2,148
  • 2
  • 32
  • 53