简体   繁体   中英

How to convert string array to long array?

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?

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.

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

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 stores each string as a long value in the LongNum array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM