各位好,小妹正在練習基礎C#語法應用,
下面的程式碼是練習,但總覺得太冗長了,想用更簡潔的語法呈現,不知道前輩們有何解?
Console.WriteLine("寫一支程式輸入3個整數,輸出這3個數的乘積");
int a = 0;
int b = 0;
int c = 0;
Console.WriteLine("輸入三個整數,並用','隔開: ");
string[] str = Console.ReadLine().Split(','); //讀取玩家輸入的字串設定為str
string str_a = str[0];
string str_b = str[1];
string str_c = str[2];
bool number_a = int.TryParse(str_a, out a);
bool number_b = int.TryParse(str_b, out b);
bool number_c = int.TryParse(str_c, out c);
int product = a * b * c;
Console.WriteLine("{0}x{1}x{2} = {3}",a,b,c,product);
Console.ReadLine();
如果要滿足你期望的輸出格式. 可以使用迴圈來完成.
List<string> numbers= new List<string>();
int summary = 1;
foreach (var input in str)
{
numbers.Add(input);
summary *= int.TryParse(input, out int val)?val:0;
}
Console.WriteLine($"{string.Join("x",numbers)} = {summary}");
但是我個人會寫一個Extension Method
.
public static class Extension
{
public static int Multiplication(this IEnumerable<int> source)
{
int result = 1;
foreach (var input in source)
result *= input;
return result;
}
}
使用起來如下.
string[] str = Console.ReadLine().Split(','); //讀取玩家輸入的字串設定為str
var result = str.Select(x => int.TryParse(x, out int val) ? val : 0)
.Multiplication();
Console.WriteLine($"{string.Join("x",str)} = {result}");
我沒寫過C#
如果以swift
來說,我會這樣寫
簡易
"1,2,3".split(separator: ",").map{Int($0) ?? 1}.reduce(1) { $0 * $1}
詳細
"1,2,3".split(separator: ",")
.map({ (string) -> Int in
return Int(string) ?? 1
}).reduce(1, { (result, value) -> Int in
return result * value
})
PS. (也許?)你可以用對照表找出相映寫法
“Map” => Select方法
“Reduce” => Aggregate方法