How to convert a string array to a long array?

At the moment I have a problem, I have this array of strings:

string[] StringNum = { "4699307989721714673", "4699307989231714673", "4623307989721714673", "4577930798721714673" }; 

I need to convert them. For a long array data type in C #:

 long[] LongNum= { 4699307989721714673, 4699307989231714673, 4623307989721714673, 4577930798721714673 }; 

But I have no idea how this is possible?

+5
source share
5 answers

You can use the simple Linq extension functions.

 long[] LongNum = StringNum.Select(long.Parse).ToArray(); 

or you can use long.TryParse for each row.

 List<long> results = new List<long>(); foreach(string s in StringNum) { long val; if(long.TryParse(s, out val)) { results.Add(val); } } long[] LongNum = results.ToArray(); 
+7
source

This can probably be done in less code with Linq, but here's the traditional method: loop each line, convert it to long:

 var longs = new List<Long>(); foreach(var s in StringNum) { longs.Add(Long.Parse(s)); } return longs.ToArray(); 
+3
source
 var longArray = StringNum.Select(long.Parse).ToArray(); 

enter image description here

+2
source

If you are looking for the fastest way with the least memory usage, then here

 string[] StringNum = { "4699307989721714673", "4699307989231714673", "4623307989721714673", "4577930798721714673" }; long[] longNum = new long[StringNum.Length]; for (int i = 0; i < StringNum.Length; i++) longNum[i] = long.Parse(StringNum[i]); 

Using new List<long>() bad because every time it needs an extension, it reallocates a lot of memory. It is better to use new List<long>(StringNum.Lenght) to allocate enough memory and prevent new List<long>(StringNum.Lenght) memory. Allocating enough memory to the list increases performance, but since you need long[] , an additional ToArray call to List<> will again redistribute all the memory to create an array. In the other hand, you know the size of the output, and you can first create an array and perform memory allocation.

+1
source

You can iterate over the string array and convert strings to numeric using the long.Parse () function. Consider the following code:

 string[] StringNum = { "4699307989721714673", "4699307989231714673", "4623307989721714673", "4577930798721714673" }; long[] LongNum = new long[4]; for(int i=0; i<4; i++){ LongNum[i] = long.Parse(StringNum[i]); } 

This converts and saves each string as the long value in the LongNum array.

0
source

All Articles