Vasant Raval
Vasant Raval

Reputation: 303

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

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?

Upvotes: 0

Views: 96

Answers (3)

eloiz
eloiz

Reputation: 91

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.

Upvotes: 0

Vivek Nuna
Vivek Nuna

Reputation: 1

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 Array.ConvertAll.

It clearly explains the second parameter,

A Converter<TInput,TOutput> that converts each element from one type to another type.

You can also refer to this declaration in the Array class.

enter image description here

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

Upvotes: 2

Natrium
Natrium

Reputation: 31204

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.

Upvotes: 1

Related Questions