PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How to find a role name in a LIST

 November 04, 2022     c#, lambda, roles     No comments   

Issue

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


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



Answered By - Terry
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing