簡體   English   中英

將double [,]轉換為字符串並存儲在SQL Server表列中

[英]Converting double[,] to a string and storing in SQL Server table column

我有一個雙精度數組初始化如下

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並以這種方式存儲,這也使得重新初始化數組非常容易(您也可以使其異步,這樣即使沒有依賴它也不會降低應用程序的運行速度)首先被添加到數據庫)。

使用StringBuilder進行Foreach(最快的方法):

var ImageData = new StringBuilder();

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

使用方便:

var ImageData = JsonConvert.SerializeObject(zDataDifference);

嘗試OfType<double>()以獲得IEnumerable<double> ,您可以將其放入Join

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM