Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Equivalent to Python's map()? [duplicate]

Tags:

python

c#

Normally in Python 2/3 we may use the following code to split two space-separated integers into two variables:

a,b = map(int,input().split())

Is there a short C# equivalent to this? (i.e nothing as long as below)

string[] template = Console.ReadLine().Split();
a = Convert.ToInt32(template[0]);
b = Convert.ToInt32(template[1]);
like image 326
Kookie Avatar asked Oct 27 '25 11:10

Kookie


1 Answers

You could try this:

var result = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

However, the above code would crash if the input is not valid.

A more fault tolerant approach would be the following:

var result = Console.ReadLine()
                    .Split(' ')
                    .Select(input => 
                    {
                        int? output = null;
                        if(int.TryParse(input, out var parsed))
                        {
                            output = parsed;
                        }
                        return output;
                    })
                    .Where(x => x != null)
                    .Select(x=>x.Value)
                    .ToArray();
like image 80
Christos Avatar answered Oct 29 '25 01:10

Christos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!