在double [,]数组

时间:2017-08-16 16:56:26

标签: c#

我尝试将元素添加到double[,]数组中。但是它出现了一些问题。我必须在JSON中保存坐标。它看起来像这样:

{
  "Polyline": [
  {
    "name": "Line1",
    "towers": [
       [13.32, 33.12],
       [3.7, 565.5432],
       [867.762, 653.1676],
            ...
    ]
  ]
  }
}

这是代码:

public double[,] GetTowersById(List<Towers> towers)
    {
        double[,] towersCoords = new double[towers.Count-1, towers.Count-1];

        using (ZadiagDBEntities context = new ZadiagDBEntities())
        {
            //List<Towers> tower = new List<Towers>();
            foreach (var item in towers)
            {
                int counter = 0;
                var tower = context.Towers.First(t => t.ID == item.ID);     // it is an object like Tower tower = new Tower(); with properties tower.Lat and tower.Long (their type is double)
                object currentElem = new double[]{ Convert.ToDouble(tower.Lat), Convert.ToDouble(tower.Long) };
                towersCoords.SetValue(currentElem, counter, counter);
                counter++;
            }
            //tower = context.Towers.Where(t => t.ID == towers[i].ID).ToList();


            }

错误消息:

  

数组不是单维的

1 个答案:

答案 0 :(得分:0)

<强>问题:

您的代码存在的问题。 towersCoords是类型double

的二维数组
double[,] towersCoords = new double[towers.Count-1, towers.Count-1];

在循环内部,您要将此对象(currentEle类型array)添加/分配到towersCoords

object currentElem = new double[]{ Convert.ToDouble(tower.Lat), Convert.ToDouble(tower.Long) };

towersCoords.SetValue(currentElem, counter, counter);

哪个错了。由于它是double类型的数组,因此无法接受array类型的对象

它可以接受以下项目:

towersCoords.SetValue(5, counter, counter);

否则,如果您需要将array放在此2D数组中,则必须更改其类型。

建议的解决方案:

以下是您可以采取其他方式的方法。由于currentElem只包含Lat和Long,所以对我来说它似乎更适合作为自定义的Struct对象。 创建临时结构。

struct TowerCoordiantes
{
    public double Lat;
    public double Long;

    public TowerCoordiantes(double pLat, double pLong)
    {
        this.Lat = pLat;
        this.Long = pLong;
    }
}

towersCoords的类型将变为:

TowerCoordiantes[,] towersCoords = new TowerCoordiantes[towers.Count-1, towers.Count-1];

currentElem的定义也改变了:

TowerCoordiantes currentElem = new TowerCoordiantes(Convert.ToDouble(tower.Lat), Convert.ToDouble(tower.Long));

然后这一行将按预期工作。

towersCoords.SetValue(currentElem, counter, counter);