如何将锯齿状双数组转换为字符串然后再返回?

时间:2012-06-08 18:25:02

标签: c# multidimensional-array

我有一个锯齿状的双打数组,我需要将其转换为我可以添加到xml文档然后转回锯齿状数组的东西。有人知道这样做的方法吗?提前谢谢。

 public double[][] Coordinates { get; set; }

 //For context this is how I'm creating the array

 //convert the geography column back in lat\long points
 for (var g = 1; g <= geography.STNumGeometries(); g++)
 {
     var geo = geography.STGeometryN(g);
     var points = new List<double[]>();
     for (var i = 1; i <= geo.STNumPoints(); i++)
     {
         var point = new double[2];
         var sp = geography.STPointN(i);
         // we can safely round the lat/long to 5 decimal places 
         // as thats 1.11m at equator, reduces data transfered to client
         point[0] = Math.Round((double) sp.Lat, 5);
         point[1] = Math.Round((double) sp.Long, 5);
         points.Add(point);
     }

     transitLineSegment.Coordinates = points.ToArray();
 }

2 个答案:

答案 0 :(得分:3)

linq的强大功能(根据评论中的建议修改代码)

var doubleAR = new List<List<Double>>()
{
   new List<double>(){ 12.5, 12.6, 12.7 },
   new List<double>(){ .06 },
   new List<double>(){ 1.0, 2.0 }
};

   var asXml = new XElement("Data",
                            doubleAR.Select(sList => new XElement("Doubles", sList.Select (sl => new XElement("Double", sl) )))
                           );

    Console.WriteLine ( asXml );
/* Output
<Data>
  <Doubles>
    <Double>12.5</Double>
    <Double>12.6</Double>
    <Double>12.7</Double>
  </Doubles>
  <Doubles>
    <Double>0.06</Double>
  </Doubles>
  <Doubles>
    <Double>1</Double>
    <Double>2</Double>
  </Doubles>
</Data> */

// Then back
   List<List<Double>> asDoubleArray =
         XDocument.Parse( asXml.ToString() )
                  .Descendants("Doubles")
                  .Select (eDL => eDL.Descendants("Double")
                                     .Select (dl => (double) dl))
                                      .ToList())
                  .ToList();

答案 1 :(得分:0)

您需要序列化对象以将其存储为字符串。下面是一个例子:http://support.microsoft.com/kb/815813