如何使用数据列表作为键值对

本文关键字:键值对 列表 何使用 数据 | 更新日期: 2023-09-27 18:17:41

我有nodeID_List;nodeX_List;nodeY_List;nodeZ_List;这些列表,第一个是整型列表,另外三个是双精度列表。我如何创建一个字典,其中键将是列表中的每个int,而3个double将是键的值。我尝试使用元组,但我无法正确格式化它。

Tuple<int, double, double, double> tuple_NodeData;
        nodeData_List = this.GetNodeInfo();
        nodeID_List = this.GetNodeIDInfo();
        nodeX_List = this.GetNodeXInfo();
        nodeY_List = this.GetNodeYInfo();
        nodeZ_List = this.GetNodeZInfo();
        for (int iNode = 0; iNode < nodeData_List.Count; iNode++)
        {
            tuple_NodeData = new Tuple<int, double, double, double>
                  (nodeID_List[iNode], nodeX_List[iNode], nodeY_List[iNode], nodeZ_List[iNode]);
        }

如何使用数据列表作为键值对

您的字典类型应该是IDictionary<int, Tuple<double, double, double>>。剩下的代码几乎是正确的,您只需要将元组添加到字典中。

    var dict = new Dictionary<int, Tuple<double, double, double>>();
    nodeData_List = this.GetNodeInfo();
    nodeID_List = this.GetNodeIDInfo();
    nodeX_List = this.GetNodeXInfo();
    nodeY_List = this.GetNodeYInfo();
    nodeZ_List = this.GetNodeZInfo();
    for (int iNode = 0; iNode < nodeData_List.Count; iNode++)
    {
      dict.add(
        nodeID_List[iNode],
        new Tuple<double, double, double>(nodeX_List[iNode], nodeY_List[iNode], nodeZ_List[iNode]));
    }

这样行吗?

Dictionary<int, double[]> dict = new Dictionary<int, double[]>();
for (int i = 0; i <  nodeID_List.Count; i++) {
  dict.Add(nodeID_List[i], new double[] {nodeX_List[i], nodeY_List[i], nodeZ_List[i]});
}

然而,我建议你把X, Y和Z放到一个新的类中:

public class Coordinate {
  public double X {get;set;}
  public double Y {get;set;}
  public double Z {get;set;}
  public Coordinate(double _x, double _y, double _z) {
    X = _x;
    Y = _y;
    Z = _z;
  }
}

然后这样做:

Dictionary<int, Coordinate> dict = new Dictionary<int, Coordinate>();
for (int i = 0; i <  nodeID_List.Count; i++) {
  dict.Add(nodeID_List[i], new Coordinate(nodeX_List[i], nodeY_List[i], nodeZ_List[i]));
}

之后,您可以使用键从该字典中检索数据,这将获得一个坐标:

Coordinate coor = dict[5]; // Select coordinate with ID = 5

之后你可以使用:

得到坐标
int x = coor.X;
int y = coor.Y;
int z = coor.Z;