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?
Split String into Array with split() The split() method is used to divide a string into an ordered list of two or more substrings, depending on the pattern/divider/delimiter provided, and returns it.
There are many methods for converting a String to a Long data type in Java which are as follows: Using the parseLong() method of the Long class. Using valueOf() method of long class. Using constructor of Long class.
We can convert String to long in java using Long. parseLong() method.
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();
var longArray = StringNum.Select(long.Parse).ToArray();
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With