如何从 C# 中的 foreach 循环的输出创建一个数组?

How to make an array from the outputs of an foreach loop in C#?

我需要将所有foreach的输出(例如p.X[0])放在一个数组中来完成计算过程并求解常微分方程,因为p.x[0 ] 随着时间的推移而变化,我需要一个数组来保存它们。 我知道将一些数据放入数组的最佳方法是 "for loop",但是当您使用 Microsoft Oslo 库时,您必须根据 Oslo 用户指南以这种方式编写这些代码。 如果您知道另一种求解这些 ode 方程的方法可以帮助我处理输出,我真的很感激! 谢谢你的帮助。 这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Research.Oslo;

namespace odestiff
{
    class Program
    {
        static void Main(string[] args)
        {
            //kinetic constant
           double ka = 200; double ki = 200; double kp = 258.3; double ktrm = 0.0072;
           double ktrh = 0.12; double ktrb = 0.00004; double kd = 0.00001;

            //initial value
            //Ti0 = 1e-5; Al0 = 1e-4;
            //Mo0 = 2; H20 = 1e-2; C0 = 0; M00 = 0; M10 = 0; M20 = 0;
            //L00 = 0; L10 = 0; L20 = 0;

            var sol = Microsoft.Research.Oslo.Ode.GearBDF(
           0,
           new Vector(0.00001, 0.0001, 2, 0.01, 0, 0, 0, 0, 0, 0, 0),
            (t, x) => new Vector(
            -ka * x[0] * x[1],
            -ka * x[0] * x[1],
            -ktrh * x[2] * x[5],
            -x[3] * x[5] * (kp + ktrm) - ki * x[3] * x[4],
             ka * x[0] * x[1] - ki * x[3] * x[4] + (ktrh * x[2] + ktrb) * x[5],
             ki * x[4] * x[3] - x[5] * (ktrh * x[2] + ktrb + kd),
             ki * x[4] * x[3] - x[6] * (ktrh * x[2] + ktrb + kd + ktrm * x[3]) + (ktrm + kp) * x[3] * x[5],
             ki * x[4] * x[3] - x[7] * (ktrh * x[2] + ktrb + kd + ktrm * x[3]) + (ktrm + kp) * x[3] * x[5] + 2 * x[6] * kp * x[3],
             x[5] * (ktrh * x[2] + ktrb + kd + ktrm * x[3]),
             x[6] * (ktrh * x[2] + ktrb + kd + ktrm * x[3]),
             x[7] * (ktrh * x[2] + ktrb + kd + ktrm * x[3])),
             new Options
             {
                 AbsoluteTolerance = 1e-6,
                 RelativeTolerance = 1e-6
             }).TakeWhile(p => p.T <= 7200).ToArray();
            foreach (var p in sol)
                Console.WriteLine("{0}", p.X[0]);
            foreach (var p in sol) 
                Console.WriteLine("{0}", p.X[0]);
            Console.ReadLine();

你打印了两次p.X[0],不是很清楚。但是要获得一个数组,您可以使用 Linq:

double[] values = sol.Select(p => p.X[0]).ToArray();