【C#の基本】リスト、辞書、そしてforeachの使い方を理解しよう!
こんにちは、サルモリです。
C#におけるリスト、辞書、そしてforeachの使い方を解説します。これらは、C#の基本となる要素で、データの集合を効率よく管理するために必須の知識です。

リストの基本
まずは、「List」についてです。
Listは、配列と同じように複数のデータをまとめて管理することができるクラスです。しかし、Listの方が配列よりも便利な機能がいくつかあります。

Listの作成と操作
ソースコード例
1 2 3 4 5 6 7 |
List<string> list = new List<string>(); list.Add("Apple"); list.Add("Banana"); list.Add("Cherry"); foreach (string fruit in list) { Console.WriteLine(fruit); } |
出力結果
Apple
Banana
Cherry
ポイント
Listはデータの追加が簡単にでき、順番に並んでいます。

KindleUnlimited会員であれば、全ての本をご覧頂けます。 Linqを理解すれば、C#プログラミングの世界が変わる 第1版
-188x300.jpg)
辞書の基本
次に、「Dictionary」について解説します。
Dictionaryは、キーと値をペアで管理するためのクラスです。一つのキーに対して一つの値が対応します。

Dictionaryの作成と操作
ソースコード例
1 2 3 4 5 6 7 |
Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("Apple", "Red"); dict.Add("Banana", "Yellow"); dict.Add("Cherry", "Red"); foreach (KeyValuePair<string, string> fruit in dict) { Console.WriteLine(fruit.Key + ": " + fruit.Value); } |
出力結果
Apple: Red
Banana: Yellow
Cherry: Red
ポイント
Dictionaryはキーと値のペアでデータを管理します。キーを指定すれば、対応する値を瞬時に取り出すことが可能です。

foreachの基本
最後に、「foreach」について解説します。
foreachは、コレクションの各要素を順に処理するための制御構文です。

foreachの使用例
ソースコード例
1 2 3 4 |
string[] fruits = {"Apple", "Banana", "Cherry"}; foreach (string fruit in fruits) { Console.WriteLine(fruit); } |
出力結果
Apple
Banana
Cherry
ポイント
foreachを使えば、ListやDictionaryのすべての要素を簡単に順に処理することができます。

まとめ
以上、C#における「List」、「Dictionary」、「foreach」の基本について説明しました。
これらの知識を理解し、活用すれば、より効率的かつ簡潔なプログラミングが可能になります。
もちろん、これらのコンセプトは他のプログラミング言語でも共通していますので、一度理解してしまえば、他の言語を学ぶときにも役立つでしょう。


最後まで読んで頂き、ありがとうございました。少しでもお役に立てたなら幸いです!
