【发布时间】:2017-12-10 20:49:58
【问题描述】:
我对 C# 比较陌生,所以请原谅之前提出的问题。
我需要在循环中“即时”填充数组元素(例如,double[])。我知道最大数组长度,但直到运行时才知道单个数组值。
我有这段代码初始化包含数组元组的字典。给定具有空槽的元组中的数组分配,如何在生成数据时将双精度或字符串添加到元组中的适当数组?
我在下面的代码中标记了我的问题。
public void Execute(SceneNode Parent)
{
int maxAircraft = 10000;
string vehicleState = "";
double vehicleAlt;
double vehicleVR;
double vehicleTime;
Dictionary<string, Tuple<double[], double[], double[], string[]>> flightData
= new Dictionary<string, Tuple<double[], double[], double[], string[]>>(maxAircraft);
//initializes flight state data dictionaries
// flightList is a string[] already populated
flightData = initializeFlightData(flightList, maxRecordCount);
//let's say that we start obtaining data for each entry in the dictionary
foreach( var item in flightData )
{
//get the current values for the vehicle item at this time
vehicleState = getVehicleStateMethod( item );
vehicleAlt = getVehicleAltMethod( item );
vehicleVR = getVehicleVrMethod( item );
vehicleTime = getVehicleTimeMethod( item );
var thisFlightData = flightData[aircraftName] as Tuple<double[], double[], double[], string[]>;
//------------------------------------------------------
***// Question: how do I progressively add the values (vehicle*)
// to each respective array such that the arrays are updated
// (e.g., new value at bottom) with each new set of values?
//------------------------------------------------------***
}
}
//------------------------------------------------------------------------
private Dictionary<string, Tuple<double[], double[], double[], string[]>> initializeFlightData(string[] flightList, int maxRecordCount)
{
//values for the arrays are unknown at this point
double[] dt = new double[maxRecordCount];
double[] vr = new double[maxRecordCount];
double[] FL = new double[maxRecordCount];
string[] altState = new string[maxRecordCount];
var flightStateData = new Tuple<double[], double[], double[], string[]>(dt, vr, FL, altState);
Dictionary<string, Tuple<double[], double[], double[], string[]>> flightData
= new Dictionary<string, Tuple<double[], double[], double[], string[]>>(flightList.Count());
for (int i = 0; i < flightList.Count(); i++)
{
flightData.Add(flightList[i], flightStateData);
}
return flightData;
}
//----------------------------------------------------------------------------
【问题讨论】:
-
不要使用元组,不要使用数组。使用一个类的列表。该列表可以根据需要调整大小,并且该类可以具有描述其含义的命名属性,而不是
Item1等。您拥有的这段代码太神秘而无法使用。此外,使用 x 个并行数组/列表比使用一个具有 x 个属性的类的列表要少得多。 -
OP,您是否有 C 或 C++ 背景?它与您的问题无关,但它可以解释您对数组的喜爱。
-
添加到@EdPlunkett - 最好定义一个类,其属性为
List<double>,另一个List<double>,依此类推。一个原因是您可以为这些属性命名,这样字典中的内容就不会那么混乱了。我们可以查看字典,而不必同时尝试理解字典中的内容。更长的变量名也是一个好主意。它的工作原理相同,但只是让大脑更容易。如果太多东西一下子让人困惑,那么大脑就必须更加努力地处理它。 -
我可以放弃 Tuple 构造。由于我的 Matlab 背景,我喜欢数组,尤其是。单元阵列。要回复 Steve H.,您是说我的字典应该像 Dictionary
> 之后使用 *.Add 方法?正如stackoverflow.com/questions/1596530/… 所述。 -
@BenjaminLevy a
List<T>只接受一个类型参数。因此,您需要创建一个具有每个这些值的属性的类,或者一个具有多个列表的类(以您的上下文中更有意义的为准)。
标签: c# arrays loops dictionary tuples