Home > Software design >  What does x=>(int)x - 48 mean when you add a number to a digit array?
What does x=>(int)x - 48 mean when you add a number to a digit array?

Time:11-16

so im taking number input and the im trying to add each digit to an array of int without using any loop

here i got an answer

int[] fNum = Array.ConvertAll(num.ToString().ToArray(),x=>(int)x - 48);

I understand until .toarray(), but I do not understand why it takes a new variable x and the => (int)x - 48.

Could anyone explain this to me?

CodePudding user response:

Because the asci value of 0 is 48 and for 1 it is 49. so to get the char value 1 you need to do 49 - 48 which is equal to 1 and similarly for other numbers.

you should also look in to the documentation of enter image description here

Also, have a look to understand lambda operator and the official documentation.

CodePudding user response:

without using any loop

Well, I might have a surpise for you.

a new variable x

ConvertAll is actually a loop under the hood. It iterates through the collection. x represents an item in the collection.

x=>(int)x - 48

For each item x in the collection, cast it to an int and subtract 48.

This syntax is a lambda expression.

CodePudding user response:

num.ToString().ToArray(),x=>(int)x - 48

This code is process of dividing a string filled with numbers into an array of characters, converting CHAR-type characters into ASCII values, and converting them into Int values.

The letter '5' of the CHAR type is an ASCII value of 53 and must be -48 to convert it to a INT type value 5.

  • Related