0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

プログラミング練習記録 4日目:C#:配列、List、Dictionary、メソッド

Posted at

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}さん!");
}

出力結果
こんにちは、山田さん!

まとめ

用途によって、使い方を変えないとパフォーマンスにかなり影響があるので気を付けたいです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?