回答編集履歴

3

説明を追加

2016/04/06 22:32

投稿

raccy
raccy

スコア21733

test CHANGED
@@ -1,4 +1,6 @@
1
1
  こういうのでしょうか?
2
+
3
+
2
4
 
3
5
  ```C#
4
6
 
@@ -53,3 +55,15 @@
53
55
  }
54
56
 
55
57
  ```
58
+
59
+
60
+
61
+ これが「見やすい」かどうかは人それぞれだと思います。Linqや関数型プログラミングに慣れている人はこちらの方がより「見やすい」と感じるでしょうが、そうで無い人にとっては逆にわかりづらく思えるかも知れません。
62
+
63
+
64
+
65
+ この書き方は「見やすい」こと以外に利点があります。それは、「書き換えやすい」ことです。たとえば、新たに"lemon"について"yellow"を足したくなったとしましょう。if文の時は分岐を増やして、また同じ事を書く必要がありますが、こちらでは`fruitColor`というDictionaryに`{"lemon", "yellow"}`を追加するだけで終わります。他にも、"color is ..."というところを"色は...です。"に書き換えたいとか、大文字小文字を無視したいとか、表示するのは最初の数個までにしたいとか、表示の方法を変えたいとかいうとき、ほとんどの場合が1行書き換えるか、追加するだけで済みます。
66
+
67
+
68
+
69
+ しかし、最初に言ったとおり、これはLinqや関数型プログラミングに慣れていることが前提です。慣れれば簡単ですが、慣れない内は難しいと感じるかと思いますので、全ての人に勧められるわけではありません。

2

List<T>を使うようにしました。型推論を使うようにしました。

2016/04/06 22:32

投稿

raccy
raccy

スコア21733

test CHANGED
@@ -16,9 +16,19 @@
16
16
 
17
17
  {
18
18
 
19
- string[] fruits = new string[] {"fuji apple", "wild strawberry", "hassaku orange", "forbidden fruit"};
19
+ var fruits = new List<string> {
20
20
 
21
+ "fuji apple",
22
+
23
+ "wild strawberry",
24
+
25
+ "hassaku orange",
26
+
27
+ "forbidden fruit",
28
+
29
+ };
30
+
21
- Dictionary<string,string> fruitColor = new Dictionary<string,string>(){
31
+ var fruitColor = new Dictionary<string, string>() {
22
32
 
23
33
  { "apple", "red" },
24
34
 

1

Dictionaryを直接Linqすることにして、見つからない場合でも例外にならないようにしました。

2016/04/06 22:17

投稿

raccy
raccy

スコア21733

test CHANGED
@@ -16,7 +16,7 @@
16
16
 
17
17
  {
18
18
 
19
- string[] fruits = new string[] {"fuji apple", "wild strawberry", "hassaku orange"};
19
+ string[] fruits = new string[] {"fuji apple", "wild strawberry", "hassaku orange", "forbidden fruit"};
20
20
 
21
21
  Dictionary<string,string> fruitColor = new Dictionary<string,string>(){
22
22
 
@@ -30,7 +30,7 @@
30
30
 
31
31
  fruits
32
32
 
33
- .Select(fruit => fruitColor[fruitColor.Keys.Where(f => fruit.Contains(f)).First()])
33
+ .Select(fruit => fruitColor.FirstOrDefault(kv => fruit.Contains(kv.Key)).Value)
34
34
 
35
35
  .Select(color => "color is "+ color)
36
36
 
@@ -42,6 +42,4 @@
42
42
 
43
43
  }
44
44
 
45
-
46
-
47
45
  ```