如何将锯齿状双数组转换为字符串并再次返回? [英] How to convert a jagged double array to a string and back again?

查看:38
本文介绍了如何将锯齿状双数组转换为字符串并再次返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a jagged array of doubles that I need to convert to something I can add to an xml document then turn back into the jagged array. Anyone know of a way to do this? Thanks in advance.

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

推荐答案

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

The power of linq (code modified per suggestions in comments)

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

这篇关于如何将锯齿状双数组转换为字符串并再次返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆