How to convert string array to long array?
Solution 1
You could use simple Linq
extension functions.
long[] LongNum = StringNum.Select(long.Parse).ToArray();
or you can use long.TryParse
on each string.
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();
Solution 2
var longArray = StringNum.Select(long.Parse).ToArray();
Solution 3
It can probably be done in less code with Linq, but here's the traditional method: loop each string, convert it to a long:
var longs = new List<Long>();
foreach(var s in StringNum) {
longs.Add(Long.Parse(s));
}
return longs.ToArray();
Solution 4
If you are looking for the fastest way with smallest memory usage possible then here it is
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>()
is bad because every time it needs an expansion then it reallocates a lot of memory. It is better to use new List<long>(StringNum.Lenght)
to allocate enough memory and prevent multiple memory reallocations. Allocating enough memory to list increases performance but since you need long[]
an extra call of ToArray
on List<>
will do the whole memory reallocation again to produce the array. In other hand you know the size of output and you can initially create an array and do the memory allocation.
SmackDat
Well i am a Mechanical Engineering Student, i know right, why am i here coding?! well to answer that its my own passion that i would love to keep up with, not doing as if i need to make money i just love it.
Updated on June 30, 2022Comments
-
SmackDat almost 2 years
I am in bust at the moment, I have this string array:
string[] StringNum = { "4699307989721714673", "4699307989231714673", "4623307989721714673", "4577930798721714673" };
I need to convert them To long array data type in C#:
long[] LongNum= { 4699307989721714673, 4699307989231714673, 4623307989721714673, 4577930798721714673 };
But I have no idea how, is it even possible?