1.本日の作業内容
C# 基本文法:配列、List、Dictionary、メソッド 復習
2.作業目的
・復習と使い方の確認。
1.配列(Array)
配列とは...「複数のデータ(同じ型)を1つの変数でまとめて扱える構造」のこと。
宣言と初期化
// 曜日のリスト(string型)
string[] days = { "Mon", "Tue", "Wed", "Thu", "Fri" };
// 点数のリスト(int型)
int[] scores = new int[] { 80, 90, 70 };
要素へのアクセス
Console.WriteLine(days[0]);
出力結果
Mon
ループで処理
foreach (string day in days)
{
Console.WriteLine(day);
}
出力結果
Mon
Tue
Wed
Thu
Fri
2.List
List...「配列に似ているが、サイズの変更ができるコレクション」のこと。
特徴は下記の通り
- 動的に要素を追加・削除できる
- Count プロパティで長さが取れる
宣言と追加
using System.Collections.Generic;
List<string> fruits = new List<string>();
// fruitsというリストにAppleを追加
fruits.Add("Apple");
// fruitsというリストにBananaを追加
fruits.Add("Banana");
Console.WriteLine(fruits.Count);
出力結果
2
3.Dictionary
Dictionary...「キーと値のペアでデータを管理する構造」のこと。
宣言と追加
Dictionary<int, string> employees = new Dictionary<int, string>();
employees[1001] = "佐藤";
employees[1002] = "鈴木";
Console.WriteLine(employees[1002]);
出力結果
鈴木
ループ処理
foreach (var pair in employees)
{
Console.WriteLine($"ID : {pair.Key}, name : {pair.Value}");
}
出力結果
ID : 1001, name : 佐藤
ID : 1002, name : 鈴木
4.メソッド
メソッド...「繰り返し使う処理を1つにまとめたもの」のこと。
宣言
public static void Main()
{
Greet("山田");
}
static void Greet(string name)
{
Console.WriteLine($"こんにちは、{name}さん!");
}
出力結果
こんにちは、山田さん!
まとめ
用途によって、使い方を変えないとパフォーマンスにかなり影響があるので気を付けたいです。