如何在动态数组中添加项目

How to add items in a dynamic array

我需要创建一个 return 动态[]

的函数

这对我来说很好

    public static dynamic[] GetDonutSeries(this Polls p)
    {
        return new dynamic[]
            {
                new {category = "Football",value = 35},
                new {category = "Basketball",value = 25},
                new {category = "Volleyball",value = 20},
                new {category = "Rugby",value = 10},
                new {category = "Tennis",value = 10}  
            };
    }

但我需要添加执行不同操作的项目。

像这样

public static dynamic[] GetDonutSeries(this Polls p)
    {
        dynamic[] result = new dynamic[]();

        foreach (PollOptions po in p.PollOptions)
        {
            result.Add(new {category = po.OptionName,value = po.PollVotes.Count});
        }
        return result;
    }

但是我不能为动态[]使用.Add方法。我该怎么做?

数组没有 Add 方法。看来您正在寻找 List

public static List<dynamic> GetDonutSeries(this Polls p)
{
    List<dynamic> result = new List<dynamic>();

    foreach (PollOptions po in p.PollOptions)
    {
        result.Add(new { category = po.OptionName, value = po.PollVotes.Count });
    }
    return result;
}

如果你必须return一个数组,你可以使用result.ToArray()