转换List的最佳方法<tuple <double,double =“”>&gt;到[,] C#中的数组

时间:2016-09-19 18:38:47

标签: c# arrays

我正在从数据库中读取两列数据,我想创建一个multidimensional array [,]对,如

double[,] arr = new double[,] { {val1,val2},{val1,val2}...{val1,val2} };

由于我不知道数据库数据的大小,我使用的是列表

所以我有

List<Tuple<double, double>> Aux = new List<Tuple<double, double>>(); 

//THIS EMULATES READING DATABASE 
Aux.Add(new Tuple<double, double>(1.333,122.3));
Aux.Add(new Tuple<double, double>(2.343,142.3));
...
Aux.Add(new Tuple<double, double>(1.222,132.3));
if (Aux.Count > 0)
{
    int index = 0;
    foreach (Tuple<double, double> item in Aux)
    {
        res[index, 0] = item.Item1;
        res[index, 1] = item.Item2;
        index++;
    }
}

我如何获得如下结果:

double[,] arr = new double[,] { 
{ 1.333,122.3 }, 
{ 2.343,142.3 }, 
...
{1.222,132.3}
};

2 个答案:

答案 0 :(得分:1)

var inputData = Enumerable.Range(1, 10000)
                            .Select(i => Tuple.Create(10d * i, 1d * i))
                            .ToList();

{ // fastest
    var outputData = new double[inputData.Count, 2];
    var index = 0;
    foreach (var item in inputData)
    {
        outputData[index, 0] = item.Item1;
        outputData[index, 1] = item.Item2;
        index++;
    }
}

{ // slightly slower
    var outputData = new double[inputData.Count, 2];
    for (var index = inputData.Count - 1; index > -1; index--)
    {
        var tupple = inputData[index];
        outputData[index, 0] = tupple.Item1;
        outputData[index, 1] = tupple.Item2;
    }
}

{ // much slower
    var outputData = new double[inputData.Count, 2];
    foreach (var item in inputData.Select((v, i) => new { Value = v, Index = i }))
    {
        outputData[item.Index, 0] = item.Value.Item1;
        outputData[item.Index, 1] = item.Value.Item2;
    }
}

答案 1 :(得分:0)

在C#7.0或更高版本中:

var testTupleList = new List<(double, double)>() {
    (1.333,122.3),
    (2.343,142.3)
};

List<double[]> result =testTupleList.Select(data => data.ToTuple()
   .GetType()
   .GetProperties()
   .Select(property => property.GetValue(data.ToTuple()))
   .Cast<double>()
   .ToArray()).ToList();