(C#)文字列で場合分けするときは、Dictionary を使うことができる
解説
文字列の内容によって、処理を変えたい場合があります。その場合は、
① if...else...で条件分岐をする
② switch...case...で条件分岐をする
③ Dictionary で string からのマッピングを作る
などの方法があります。
今回は、日月火水木金土の文字列を入れると 0~6 の数値を出力する関数を作ってみたいと思います。
コード①
static int YoubiToNumber1(string youbi) { if(string.Equals(youbi, "日")) return 0; else if (string.Equals(youbi, "月")) return 1; else if (string.Equals(youbi, "火")) return 2; else if (string.Equals(youbi, "水")) return 3; else if (string.Equals(youbi, "木")) return 4; else if (string.Equals(youbi, "金")) return 5; else if (string.Equals(youbi, "土")) return 6; return -1; }
コード②
static int YoubiToNumber2(string youbi) { switch (youbi) { case "日": return 0; case "月": return 1; case "火": return 2; case "水": return 3; case "木": return 4; case "金": return 5; case "土": return 6; default: return -1; } }
コード③
static Dictionary<string, int> _dic = new Dictionary<string, int>() { {"日", 0},{"月", 1},{"火", 2},{"水", 3},{"木", 4},{"金", 5},{"土", 6}, }; static int YoubiToNumber3(string youbi) { try { return _dic[youbi]; } catch (Exception) { return -1; } }
補足
速度では if else が優れており、読みやすさでは switch case が優れているように思えます。
コード③は、_dic[key] = value; することにより、場合分けを動的に追加することができます。