回答編集履歴
3
説明を追加
answer
CHANGED
@@ -1,4 +1,5 @@
|
|
1
1
|
こういうのでしょうか?
|
2
|
+
|
2
3
|
```C#
|
3
4
|
using System;
|
4
5
|
using System.Linq;
|
@@ -25,4 +26,10 @@
|
|
25
26
|
.ForEach(str => Console.WriteLine(str));
|
26
27
|
}
|
27
28
|
}
|
28
|
-
```
|
29
|
+
```
|
30
|
+
|
31
|
+
これが「見やすい」かどうかは人それぞれだと思います。Linqや関数型プログラミングに慣れている人はこちらの方がより「見やすい」と感じるでしょうが、そうで無い人にとっては逆にわかりづらく思えるかも知れません。
|
32
|
+
|
33
|
+
この書き方は「見やすい」こと以外に利点があります。それは、「書き換えやすい」ことです。たとえば、新たに"lemon"について"yellow"を足したくなったとしましょう。if文の時は分岐を増やして、また同じ事を書く必要がありますが、こちらでは`fruitColor`というDictionaryに`{"lemon", "yellow"}`を追加するだけで終わります。他にも、"color is ..."というところを"色は...です。"に書き換えたいとか、大文字小文字を無視したいとか、表示するのは最初の数個までにしたいとか、表示の方法を変えたいとかいうとき、ほとんどの場合が1行書き換えるか、追加するだけで済みます。
|
34
|
+
|
35
|
+
しかし、最初に言ったとおり、これはLinqや関数型プログラミングに慣れていることが前提です。慣れれば簡単ですが、慣れない内は難しいと感じるかと思いますので、全ての人に勧められるわけではありません。
|
2
List<T>を使うようにしました。型推論を使うようにしました。
answer
CHANGED
@@ -7,8 +7,13 @@
|
|
7
7
|
{
|
8
8
|
public static void Main(string[] args)
|
9
9
|
{
|
10
|
-
|
10
|
+
var fruits = new List<string> {
|
11
|
+
"fuji apple",
|
12
|
+
"wild strawberry",
|
13
|
+
"hassaku orange",
|
14
|
+
"forbidden fruit",
|
15
|
+
};
|
11
|
-
|
16
|
+
var fruitColor = new Dictionary<string, string>() {
|
12
17
|
{ "apple", "red" },
|
13
18
|
{ "strawberry", "red" },
|
14
19
|
{ "orange", "orange" },
|
1
Dictionaryを直接Linqすることにして、見つからない場合でも例外にならないようにしました。
answer
CHANGED
@@ -7,18 +7,17 @@
|
|
7
7
|
{
|
8
8
|
public static void Main(string[] args)
|
9
9
|
{
|
10
|
-
string[] fruits = new string[] {"fuji apple", "wild strawberry", "hassaku orange"};
|
10
|
+
string[] fruits = new string[] {"fuji apple", "wild strawberry", "hassaku orange", "forbidden fruit"};
|
11
11
|
Dictionary<string,string> fruitColor = new Dictionary<string,string>(){
|
12
12
|
{ "apple", "red" },
|
13
13
|
{ "strawberry", "red" },
|
14
14
|
{ "orange", "orange" },
|
15
15
|
};
|
16
16
|
fruits
|
17
|
-
.Select(fruit => fruitColor
|
17
|
+
.Select(fruit => fruitColor.FirstOrDefault(kv => fruit.Contains(kv.Key)).Value)
|
18
18
|
.Select(color => "color is "+ color)
|
19
19
|
.ToList()
|
20
20
|
.ForEach(str => Console.WriteLine(str));
|
21
21
|
}
|
22
22
|
}
|
23
|
-
|
24
23
|
```
|