【问题标题】:how to use a list of data as keyvalue pair如何使用数据列表作为键值对
【发布时间】:2014-08-13 06:53:57
【问题描述】:

我有nodeID_ListnodeX_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]);

        }

【问题讨论】:

  • 您的代码应该可以工作(您可能希望从值中删除键)。你只需要将它添加到字典中

标签: c# list dictionary


【解决方案1】:

您的字典将是IDictionary&lt;int, Tuple&lt;double, double, double&gt;&gt; 类型。您的其余代码几乎是正确的,您只需将元组添加到字典中即可。

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

【讨论】:

  • 请帮助我展示我必须如何根据上述代码中的 id 检索数据,即 x、y、z 坐标。如果我问了愚蠢的问题,我很抱歉。在此先感谢。请尽快回复我
  • 就像您访问任何其他字典一样(请阅读 .NET 和字典的基础知识,您会在 MSDN 上找到大量资源):dict[your_node_id].Item3
【解决方案2】:

这样可以吗?

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;

【讨论】:

  • 你能告诉我如何从这本字典中检索数据吗?这可能很容易,但我做不到。提前谢谢
  • 可访问性不一致:返回类型 'System.Collections.Generic.Dictionary' 的可访问性低于方法 'TestProject.NodeInfo.GetNodeID_AlongWithCoordinates()'
  • 字典 dict = new Dictionary(); public Dictionary GetNodeID_AlongWithCoordinates() { for (int i = 0; i
  • 写得像上面一样,出现错误,请帮忙
  • 我忘记了一些“公众”,我很抱歉。请查看我的更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-15
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多