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

时间:2014-08-13 06:53:58

标签: c# list dictionary

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

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]);

        }

2 个答案:

答案 0 :(得分:0)

这会吗?

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;

答案 1 :(得分:0)

您的词典的类型为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]));
    }