Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find a role name in a LIST

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading