9

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?

5 Answers 5

14

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();
Sign up to request clarification or add additional context in comments.

Comments

5
var longArray = StringNum.Select(long.Parse).ToArray();

enter image description here

Comments

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

Comments

2

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.

Comments

0

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.

1 Comment

Note: I was writing this answer while @doctor posted his answer. Our answers are similar but I couldn't be notified when he posted his answer since I am on mobile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.