0

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Vasant Raval
  • 257
  • 1
  • 12
  • 31
  • It's a lambda expression. There's lots of information around about lambda expressions. – jmcilhinney Nov 16 '22 at 05:48
  • 1
    Does this answer your question? [What does the '=>' syntax in C# mean?](https://stackoverflow.com/questions/290061/what-does-the-syntax-in-c-sharp-mean) – Klaus Gütter Nov 16 '22 at 05:48
  • `(int)x` => convert this character from the string to it's unicode value as an integer. Note that `Array.ConvertAll` must have a loop inside it, so your program still has a loop. – Jeremy Lakeman Nov 16 '22 at 06:18
  • Side note: it should have been written as `letter => letter - '0'` and now the meaning is clear: turning characters ascii codes of `'0'..'9'` into corresponding integer values `0..9` – Dmitry Bychenko Nov 16 '22 at 09:23
  • Side note: `int[] fNum = num.ToString().Select(letter => letter - '0').ToArray();` seems to be more readable – Dmitry Bychenko Nov 16 '22 at 09:29

3 Answers3

2

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.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
1

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.

Natrium
  • 30,772
  • 17
  • 59
  • 73
  • No. => means: with this item x and the lefthand side of the arrow we are going to perform the action on the righthand side of the arrow. – Natrium Nov 16 '22 at 05:51
0
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.

eloiz
  • 81
  • 9