【问题标题】:How to add items in a dynamic array如何在动态数组中添加项目
【发布时间】:2015-11-16 15:58:11
【问题描述】:

我需要创建一个返回动态[]的函数

这对我来说很好用

    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 方法。我该怎么做?

【问题讨论】:

  • dynamic[] result = new dynamic[](); 是否编译?

标签: c# arrays oop dynamic anonymous-types


【解决方案1】:

数组没有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;
}

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

【讨论】:

  • 谢谢,对你的回答很有帮助:))
猜你喜欢
  • 2019-08-20
  • 2011-07-01
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多