-1

这段代码用两个硬编码值初始化一个数组,运行良好:

var db = new GoogleGraph {
    cols = new ColInfo[] {
        new ColInfo { id = "", label = "Date", pattern ="", type = "string" },
        new ColInfo { id = "", label = "Attendees", pattern ="", type = "number" }                       
    }.ToList(),
    rows = new List<DataPointSet>()
};
db.cols.AddRange(listOfValues.Select(p => new ColInfo { id = "", label = p, type = "number" }));

尝试添加一些动态生成的值的代码不起作用:

var db = new GoogleGraph {
    cols = new ColInfo[] {
        new ColInfo { id = "", label = "Date", pattern ="", type = "string" },
        new ColInfo { id = "", label = "Attendees", pattern ="", type = "number" },
        listOfValues.Select(p => new ColInfo { id = "", label = p, type = "number" })                     
    }.ToList(),
    rows = new List<DataPointSet>()
};

如何正确实现上述代码段?

4

1 回答 1

1

您不能将 an 传递IEnumerable<T>给这样的初始化T[]程序。

您可以通过将硬编码对象放入它们自己的集合中,然后连接动态对象来做您想做的事情:

var db = new GoogleGraph {
    cols = 
        new ColInfo[] {
            new ColInfo { id = "", label = "Date", pattern ="", type = "string" },
            new ColInfo { id = "", label = "Attendees", pattern ="", type = "number" }
        }
        .Concat(listOfValues.Select(p => 
            new ColInfo { id = "", label = p, type = "number" }))                     
        .ToList(),
    rows = new List<DataPointSet>()
};
于 2014-09-25T05:10:54.077 回答