将 double[,] 转换为字符串并存储在 SQL Server 表列中



>我有一个双精度数组初始化如下

double[,] zDataDifference = new double[2048, 2048];

为了将此数据存储在 SQL Server 表列中,我正在尝试将其转换为字符串。最初我想使用以下代码将我的 double[] 转换为字符串并成功做到这一点。

String.Join(",", NICorrectedMean.Select(p => p.ToString()).ToArray());

但是由于double[,]即(double[](没有Select方法的定义,并且不存在扩展方法...

我不想使用以下 foreach 循环,因为整个应用程序由于大量数据而挂起。

foreach(double dd in zDataRedDouble)
{
    ImageData += String.Join(",", dd);
}

有没有快速或有效的方法将double[*,*]转换为 C# 中的字符串?

foreach 解决方案运行缓慢的原因是您使用 String,并为循环的每次迭代(4,194,304 次迭代(执行字符串串联。通过使用 StringBuilder,您可以显著提高性能。如果易用性很重要,我会将其序列化为 json 并以这种方式存储它,这也使得重新初始化数组变得非常容易(您也可以使其异步,这样如果没有任何内容依赖于首先将其添加到数据库,它不会减慢您的应用程序速度(。

Foreach 使用 StringBuilder(最快的方法(:

var ImageData = new StringBuilder();
foreach (var dd in zDataDifference)
{
   ImageData.Append(dd + ",");
}

易用性:

var ImageData = JsonConvert.SerializeObject(zDataDifference);

尝试OfType<double>()以获得可以放入Join IEnumerable<double>

double[,] zDataDifference = new double[2048, 2048];
...
string result = string.Join(",", zDataDifference.OfType<double>());

但要小心:2048 * 2048 == 4194304项目意味着大量的内存(和时间(

编辑:StringBuilder解决方案(基于凯文的答案(

   // In order NOT to reallocate the memory in the process, 
   // let's estimate imageData size in anvance.
   // Let us expect each item to be not more than of 20 characters
   var ImageData = new StringBuilder(2048 * 2048 * 20);
   foreach (var item in zDataDifference) {
     // We should add ',' before each item except the very first one
     if (ImageData.Length > 0)
       ImageData.Append(',');
     // Try to avoid creating a lot of small strings: item + ","
     ImageData.Append(item);
   }
   string result = ImageData.ToString();

最新更新