1

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")
             }
StarLord
  • 707
  • 1
  • 8
  • 21
  • 7
    `var claim = new List` not `var claim = new[]` (which would initialize an array). If you need an array at the end you can call `claim.ToArray();`. Can I suggest you name your variables to be clearer (it's a collection, so it shouldbe plural: `claims`). It makes reading the code later much easier. – ProgrammingLlama Feb 01 '21 at 04:16
  • @StarLord, any update? Does my reply has helped you? – Brando Zhang Feb 09 '21 at 01:46
  • @Brando Zhang Yes, this worked for me. – StarLord Feb 09 '21 at 07:44

1 Answers1

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");
Brando Zhang
  • 22,586
  • 6
  • 37
  • 65