简体   繁体   English

如何在 C# 中使用 foreach 循环向声明数组添加新声明?

[英]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.我想在 foreach 循环中向声明数组添加新声明。 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.我最后想要的是这样的,其中 Role_1、Role_2 等来自 userRole 列表。

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

As John says, the array in C# doesn't contain add method.正如约翰所说, C# 中的数组不包含 add 方法。 It only contains append method.它仅包含 append 方法。

If you want to add new element into array, you should use append instead of add.如果要将新元素添加到数组中,则应使用 append 而不是添加。

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:或者您可以使用List<Claim>而不是var claims = new[] ,如下所示:

        var claim = new List<Claim>();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM