How to add new claims to claim array using foreach loop in C#?

I want to add new claims to a claim array in a foreach loop. How to do that?

        //userRoles is a list of string contains roles. 
        var userRoles = _repository.GetRolesOfUser(username); 
        var claim = new[]
        {
            new Claim("username", username)
                                                 
        };
        //I want to add new claims to claim like below. 
        //When I put Add I am getting error like this
        // "Claim[] doesn't contain definition for Add." 
        foreach(var userRole in userRoles)
        {
            claim.Add(new Claim("roles", userRole)); 
        }

What I want at the end is something like this where Role_1, Role_2 etc are from the userRole list.

var claim = new[]
            {
                new Claim("username", username)                    
                new Claim("roles", "Role_1")
                new Claim("roles", "Role_2")
                new Claim("roles", "Role_3")
                new Claim("roles", "Role_4")
             }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

As John says, the array in C# doesn’t contain add method. It only contains append method.

If you want to add new element into array, you should use append instead of add.

More details, you could refer to below test demo codes:

        var claims = new[]{
        new Claim("username", "aaa")

    };
        claims.Append(new Claim("aaa","aaa"));

Your codes should like this:

    //userRoles is a list of string contains roles. 
    var userRoles = _repository.GetRolesOfUser(username); 
    var claim = new[]
    {
        new Claim("username", username)
                                             
    };
    //I want to add new claims to claim like below. 
    //When I put Add I am getting error like this
    // "Claim[] doesn't contain definition for Add." 
    foreach(var userRole in userRoles)
    {
        claim .Append(new Claim("roles", userRole));
    }

Or you could use List<Claim> instead of var claims = new[], like below:

        var claim = new List<Claim>();

        claim.Add("username", "aaa");
        claim.Add("username", "bbbb");


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x