如何在两个列表/数组上正确执行算术运算

时间:2018-12-25 05:33:18

标签: c# arrays list linq

我有2Arrays个双打,需要在上面执行算术运算(+,-,/,*)

Array1 = d1 , d2, d3, d4, d5, d6,  ,   , d9, d10
Array2 =          d3, d4,   , d6,  , d8, d9, d10
Operation = "+";

修改 上方显示的空白元素仅用于表示数据 它们都没有空白存储

Array1 = d1, d2, d3, d4, d5, d6, d9, d10
Array2 = d3, d4, d6, d8, d9, d10

要求输出

ArrayOpt = 

[0] = d3+d3

[1] = d4+d4;

[2] = d5+d4;

[3] = d6+d6;

[4] = d6+d8;

[5] = d9+d9;

[6] = d10+d10;

我尝试过的事情

  int i = 0, PreviousIndex = -1;
   int SecondaryIndex = 0;

 // check if there is a gap
if (SecondaryIndex < DATES2.Length && Convert.ToInt32(d) != Convert.ToInt32(DATES2[SecondaryIndex]))
{
        // first value of index contain the index of second symbol date that matches with first symbol's first date.
        // eg: first data     => d1 d2 d3 d4 d5 d6
        //      2nd data      =>       d3 d4    d6
        // in the above case, the index would be the index of d3.
        index = DATES2.Select((v, j) => new { Index = j, Value = (int)v }).Where(p => p.Value == (int)d).Select(p => p.Index).ToList();
        if (index.Count > 0)
             SecondaryIndex = index[0];
        else
             SecondaryIndex = -1;
}

if(secondaryIndex != -1)
{
    CalculateData(operation, DATES1[i],DATES2[secondaryIndex]);
    PreviousIndex = secondaryIndex;
}
else
{
   CalculateData(operation, DATES1[i],DATES2[PreviousIndex]);
}

i++;
secondaryIndex++;

但是输出是这个

d1, d2, d3, d4, d5, d6, d9, d10
+
d3, d4, d6, d8, d9, d10

有人可以建议出什么问题或其他更好的解决方案吗?

1 个答案:

答案 0 :(得分:1)

您可以使用Math.Net库执行基本的线性代数运算以及您可能要使用的所有矩阵运算。正如您在链接中看到的所示的基本线性代数运算示例(+,*,-,/)。

此外,由于矩阵是单维的,因此可以使用单个for循环将Array1和Array2索引求和,如下所示。

var a1 = new int[5] {1,2,3,4,5}; 
var a2 = new int[7] {1,2,3,4,5,6,7};

var maxLength = a1.Length > a2.Length ? a1.Length : a2.Length;

var outputArray = new int[maxLength];

for(var i = 0; i < maxLength; i++)
{
    if(a1.Length < i + 1)
    {
        outputArray[i] = a2[i];
        continue;
    }

    if(a2.Length < i + 1)
    {
        outputArray[i] = a1[i];
        continue;
    }

    outputArray[i] = a1[i] + a2[i];
}

Console.Write(outputArray.GetValue(6));
相关问题