如何填充和编号为1到15的元素的双精度数组

时间:2011-09-08 05:52:11

标签: c# arrays

如何通过循环复制此功能。

string[] titles = new string[] { "Alpha", "Beta", "Gamma", "Delta" };
List<double[]> x = new List<double[]>();
for (int i = 0; i < titles.Length; i++)
{
 // Replace this line of code
   x.Add(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 });
}

这样我就可以使用变量,例如temp = 15,这将是双打1.0 .... 15.0

3 个答案:

答案 0 :(得分:2)

var result = titles
    .Select(t => Enumerable.Range(1, 15).Select(i => (double)i).ToArray())
    .ToList();

答案 1 :(得分:2)

如果我被允许使用LINQ那么这个怎么样?

var titles = new string[]
{
    "Alpha", "Beta", "Gamma", "Delta",
};

Func<int, double[]> makeArray = n =>
    (from i in Enumerable.Range(1, n) select (double)i)
        .ToArray();

var temp = 15;

var x = (from t in titles
         select makeArray(temp)).ToList();

答案 2 :(得分:1)

使用简单的for循环

List<double> nums = new List<double>();
for ( int i = 0; i < target; i++ ) {
    nums.Add( (double)i );
}

您可以使用Linq Enumberable类来代替循环。

using System.Linq;

int target = 15;    
var nums = Enumerable.Range(0, target).Select( x => (double)x);