我需要创建一个返回动态[]的函数
这对我来说很好
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;
}
但是我不能对 dynamic[] 使用 .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;
}
如果您必须返回一个数组,您可以使用result.ToArray()
