20
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【保存版】C#基礎100本ノック — GitHub Codespacesで学ぶC#

Posted at

はじめに

C#の基礎文法を読むだけでなく手を動かして身につけるための100問の練習問題集を作ってみました。

GitHub Codespacesを使用することで、環境構築不要でブラウザ上ですぐに学習を始められます。

すごーく長いけど、100本を全てこの記事にまとめました!!

初心者さん用に作ったのですが、ベテランさんでも眺めてみると意外と新しい発見があるかもしれません。

対象環境

  • C# 10.0以降 (.NET 6以降)
  • 推奨: .NET 8 (最新LTS版)
  • GitHub Codespaces: デフォルトで対応済

概要

  • 目的: C#の基礎文法を実践的に身につける
  • 環境: GitHub Codespaces(ブラウザ VS Code)
  • 対応デバイス: PC、タブレット、スマホはちょっと厳しい...
  • 構成: 100問(入門→応用)
  • 形式: 各問は「問題+解答例(詳細表示)」

学習範囲

  1. 基本文法(Q1〜Q20)- 変数、条件分岐、ループ
  2. 配列とコレクション(Q21〜Q35)- Array、List、Dictionary等
  3. メソッドとスコープ(Q36〜Q50)- 関数定義、デリゲート
  4. クラスとオブジェクト指向(Q51〜Q70)- OOP、継承、インターフェース
  5. 例外処理とファイル操作(Q71〜Q85)- try-catch、I/O操作
  6. LINQ入門(Q86〜Q95)- データ操作、クエリ
  7. まとめ・発展(Q96〜Q100)- DateTime、Nullable等

環境準備(GitHub Codespaces)

1. リポジトリを作成

GitHubで任意の空リポジトリ(例:csharp-100knocks)を作成します。

2. Codespacesを起動

  1. 「Code」ボタンをクリック
  2. 「Codespaces」タブを選択
  3. 「Create codespace」をクリック

c001.png

数十秒でブラウザ版 VS Code が立ち上がります!

3. コンソールプロジェクトを作成

dotnet new console -n CSharp100Knocks
cd CSharp100Knocks
dotnet run

「Hello, World!」が表示されればOK!!

c004.png

4. (任意)devcontainerで環境を固定

.devcontainer/devcontainer.json を作成:

{
  "name": "C# Codespace",
  "image": "mcr.microsoft.com/dotnet/sdk:8.0",
  "settings": { 
    "terminal.integrated.defaultProfile.linux": "bash" 
  },
  "extensions": ["ms-dotnettools.csharp"]
}

使い方のコツ

  • 基本: 1問ごとに Program.cs を書き換えて dotnet run
  • 整理したい場合: Knock01.cs などに分割し、Program.cs から呼び出し
  • ファイル操作: Codespacesコンテナ内に保存される(Git管理外)
  • 対象外: Windows依存API(WinForms/WPF)やGUI(コンソールのみ)

問題一覧

C#基礎100本ノックのカテゴリ別の一覧です。興味のあるところに飛んでもOKです!

全問題リスト

カテゴリ 問題数 内容
基本文法 Q1〜Q20 変数、条件分岐、ループ、演算子
コレクション Q21〜Q35 Array、List、Dictionary、Queue等
メソッド Q36〜Q50 関数定義、デリゲート、クロージャ
OOP Q51〜Q70 クラス、継承、インターフェース
例外・I/O Q71〜Q85 try-catch、ファイル操作、JSON/XML
LINQ Q86〜Q95 データクエリ、集計、結合
発展 Q96〜Q100 DateTime、Nullable、enum、電卓

1. 基本文法

問題 内容 学習ポイント
Q1 「Hello, World!」を出力せよ Console.WriteLine
Q2 int型の変数xに10を代入し出力せよ 変数宣言と代入
Q3 2つの数の和を出力せよ(3と5) 算術演算子
Q4 double型で割り算の結果を出力せよ(7 ÷ 2) 浮動小数点演算
Q5 bool型でtrueを出力せよ ブール型
Q6 if文でxが正なら「Positive」と出力せよ 条件分岐
Q7 偶数/奇数を判定せよ 剰余演算子
Q8 switchで 1→"One", 2→"Two", その他→"Other" switch文
Q9 forで1から5を出力せよ for文
Q10 whileで1から5を出力せよ while文
Q11 do-whileで1から5を出力せよ do-while文
Q12 三項演算子:x>=10なら"OK"、それ以外"NG" 三項演算子
Q13 AND演算子で「5以上かつ10以下」 論理AND演算子
Q14 OR演算子で「0または10」 論理OR演算子
Q15 NOT演算子:flagがfalseなら"OFF" 論理NOT演算子
Q16 constで円面積(半径2, π=3.14) const定数
Q17 文字列連結 文字列操作
Q18 文字列補間 文字列補間
Q19 null合体 ??(nullなら"Default") null合体演算子
Q20 is演算子でstring型判定 is演算子

Q1. 「Hello, World!」を出力せよ

解答例
Console.WriteLine("Hello, World!");

Q2. int型の変数xに10を代入し出力せよ

解答例
int x = 10;
Console.WriteLine(x);

Q3. 2つの数の和を出力せよ(3と5)

解答例
int a = 3, b = 5;
Console.WriteLine(a + b);

Q4. double型で割り算の結果を出力せよ(7 ÷ 2)

解答例
double result = 7.0 / 2.0;
Console.WriteLine(result);

Q5. bool型でtrueを出力せよ

解答例
bool flag = true;
Console.WriteLine(flag);

Q6. if文でxが正なら「Positive」と出力せよ

解答例
int x = 5;
if (x > 0) Console.WriteLine("Positive");

Q7. 偶数/奇数を判定せよ

解答例
int x = 7;
Console.WriteLine(x % 2 == 0 ? "Even" : "Odd");

Q8. switchで 1→"One", 2→"Two", その他→"Other"

解答例
int n = 2;
switch (n)
{
    case 1: Console.WriteLine("One"); break;
    case 2: Console.WriteLine("Two"); break;
    default: Console.WriteLine("Other"); break;
}

Q9. forで1から5を出力せよ

解答例
for (int i = 1; i <= 5; i++) Console.WriteLine(i);

Q10. whileで1から5を出力せよ

解答例
int i = 1;
while (i <= 5) { Console.WriteLine(i); i++; }

Q11. do-whileで1から5を出力せよ

解答例
int i = 1;
do { Console.WriteLine(i); i++; } while (i <= 5);

Q12. 三項演算子:x>=10なら"OK"、それ以外"NG"

解答例
int x = 12;
Console.WriteLine(x >= 10 ? "OK" : "NG");

Q13. AND演算子で「5以上かつ10以下」

解答例
int x = 7;
if (x >= 5 && x <= 10) Console.WriteLine("In range");

Q14. OR演算子で「0または10」

解答例
int x = 10;
if (x == 0 || x == 10) Console.WriteLine("Match");

Q15. NOT演算子:flagがfalseなら"OFF"

解答例
bool flag = false;
if (!flag) Console.WriteLine("OFF");

Q16. constで円面積(半径2, π=3.14)

解答例
const double PI = 3.14;
Console.WriteLine(PI * 2 * 2);

Q17. 文字列連結

解答例
Console.WriteLine("Hello" + " World");

Q18. 文字列補間

解答例
string name = "Taro";
Console.WriteLine($"名前: {name}");

Q19. null合体 ??(nullなら"Default")

解答例
string? s = null;
Console.WriteLine(s ?? "Default");

Q20. is演算子でstring型判定

解答例
object o = "test";
if (o is string) Console.WriteLine("stringです");

2. 配列とコレクション

問題 内容 学習ポイント
Q21 配列 {1,2,3} を出力せよ 配列とforeach
Q22 長さ5の配列(初期値0) 配列初期化
Q23 List の平均 ListとLINQ
Q24 Dictionary で英和1件 Dictionary
Q25 Queue の Enqueue/Dequeue Queue
Q26 Stack の Push/Pop Stack
Q27 配列を逆順 Array.Reverse
Q28 配列をソート Array.Sort
Q29 List に 3 が含まれるか Contains
Q30 TryGetValue 安全なDictionary操作
Q31 HashSet で重複排除 HashSet
Q32 最大値 Max拡張メソッド
Q33 最小値 Min拡張メソッド
Q34 List → 配列 ToArray
Q35 配列 → List ToList

Q21. 配列 {1,2,3} を出力せよ

解答例
int[] arr = {1,2,3};
foreach (var n in arr) Console.WriteLine(n);

Q22. 長さ5の配列(初期値0)

解答例
int[] arr = new int[5];
Console.WriteLine(string.Join(",", arr));

Q23. List の平均

解答例
var list = new List<int> {1,2,3,4,5};
Console.WriteLine(list.Average());

Q24. Dictionary で英和1件

解答例
var dict = new Dictionary<string,string>{{"apple","りんご"}};
Console.WriteLine(dict["apple"]);

Q25. Queue の Enqueue/Dequeue

解答例
var q = new Queue<int>();
q.Enqueue(1); 
q.Enqueue(2);
Console.WriteLine(q.Dequeue());

Q26. Stack の Push/Pop

解答例
var st = new Stack<int>();
st.Push(10); 
st.Push(20);
Console.WriteLine(st.Pop());

Q27. 配列を逆順

解答例
int[] arr = {1,2,3};
Array.Reverse(arr);
Console.WriteLine(string.Join(",", arr));

Q28. 配列をソート

解答例
int[] arr = {3,1,2};
Array.Sort(arr);
Console.WriteLine(string.Join(",", arr));

Q29. List に 3 が含まれるか

解答例
var list = new List<int>{1,2,3};
Console.WriteLine(list.Contains(3));

Q30. TryGetValue

解答例
var dict = new Dictionary<string,int>{{"a",1}};
if (dict.TryGetValue("a", out int val)) 
    Console.WriteLine(val);

Q31. HashSet で重複排除

解答例
var set = new HashSet<int>{1,2,2,3};
Console.WriteLine(string.Join(",", set));

Q32. 最大値

解答例
int[] arr = {1,5,3};
Console.WriteLine(arr.Max());

Q33. 最小値

解答例
int[] arr = {1,5,3};
Console.WriteLine(arr.Min());

Q34. List → 配列

解答例
var list = new List<int>{1,2,3};
int[] arr = list.ToArray();
Console.WriteLine(arr.Length);

Q35. 配列 → List

解答例
int[] arr = {1,2,3};
var list = arr.ToList();
Console.WriteLine(list.Count);

3. メソッドとスコープ

問題 内容 学習ポイント
Q36 Add(a,b) メソッド定義
Q37 既定値引数 デフォルトパラメータ
Q38 outで平方根 outパラメータ
Q39 refで2倍 refパラメータ
Q40 staticメソッド static修飾子
Q41 オーバーロード メソッドオーバーロード
Q42 名前付き引数 名前付き引数
Q43 params 合計 可変長引数
Q44 式本体Abs 式本体メンバー
Q45 ローカル関数 ローカル関数
Q46 Func 加算器 Func
Q47 Action 出力 Action
Q48 Predicate + FindAll Predicate
Q49 クロージャカウンタ クロージャ
Q50 refでSwap(値渡しとの違い) 参照渡しの理解

Q36. Add(a,b)

解答例
int Add(int a, int b) => a + b;
Console.WriteLine(Add(3, 5));

Q37. 既定値引数

解答例
int Mul(int a, int b = 2) => a * b;
Console.WriteLine(Mul(3));     // 6
Console.WriteLine(Mul(3, 4));  // 12

Q38. outで平方根

解答例
bool TrySqrt(double x, out double r)
{
    if (x < 0) { r = 0; return false; }
    r = Math.Sqrt(x); 
    return true;
}

if (TrySqrt(9, out double ans)) 
    Console.WriteLine(ans);

Q39. refで2倍

解答例
void Double(ref int x) => x *= 2;

int n = 5; 
Double(ref n); 
Console.WriteLine(n);

Q40. staticメソッド

解答例
static class Util 
{ 
    public static void Hello() => Console.WriteLine("Hi"); 
}

Util.Hello();

Q41. オーバーロード

解答例
int Add(int a, int b) => a + b; 
double Add(double a, double b) => a + b;

Console.WriteLine(Add(2, 3)); 
Console.WriteLine(Add(2.5, 3.1));

Q42. 名前付き引数

解答例
string Join3(string a, string b, string c) => $"{a}-{b}-{c}";

Console.WriteLine(Join3(c: "C", a: "A", b: "B"));

Q43. params 合計

解答例
int Sum(params int[] xs) => xs.Sum();

Console.WriteLine(Sum(1, 2, 3, 4)); 
Console.WriteLine(Sum());

Q44. 式本体Abs

解答例
int Abs(int x) => x >= 0 ? x : -x;

Console.WriteLine(Abs(-7));

Q45. ローカル関数

解答例
void Outer()
{ 
    int Square(int x) => x * x; 
    Console.WriteLine(Square(6)); 
}

Outer();

Q46. Func 加算器

解答例
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(10, 20));

Q47. Action 出力

解答例
Action<string> print = s => Console.WriteLine($"[{s}]");
print("Hello");

Q48. Predicate + FindAll

解答例
var list = new List<int>{1, 2, 3, 4, 5, 6};
Predicate<int> even = n => n % 2 == 0;
Console.WriteLine(string.Join(",", list.FindAll(even)));

Q49. クロージャカウンタ

解答例
Func<int> MakeCounter()
{ 
    int count = 0; 
    return () => ++count; 
}

var counter = MakeCounter(); 
Console.WriteLine(counter()); // 1
Console.WriteLine(counter()); // 2
Console.WriteLine(counter()); // 3

Q50. refでSwap(値渡しとの違い)

解答例
void Swap(ref int a, ref int b) 
{ 
    (a, b) = (b, a); 
}

void TrySwapByValue(int a, int b) 
{ 
    (a, b) = (b, a); 
}

int x = 1, y = 2;

// 値渡し - 元の変数は変わらない
TrySwapByValue(x, y); 
Console.WriteLine($"{x},{y}"); // 1,2

// 参照渡し - 元の変数が変わる
Swap(ref x, ref y); 
Console.WriteLine($"{x},{y}"); // 2,1

4. クラスとオブジェクト指向

問題 内容 学習ポイント
Q51 Person.Name プロパティ
Q52 必須コンストラクタ コンストラクタ
Q53 カプセル化(privateフィールド) アクセス修飾子
Q54 自動実装プロパティ初期値 自動プロパティ
Q55 読み取り専用プロパティ + 面積 読み取り専用プロパティ
Q56 init 専用プロパティ init専用プロパティ
Q57 ToString オーバーライド メソッドオーバーライド
Q58 継承と override 継承とポリモーフィズム
Q59 抽象クラス 抽象クラス
Q60 インターフェース インターフェース
Q61 明示的インターフェース実装 明示的実装
Q62 sealed クラス sealed修飾子
Q63 静的メンバーでインスタンス数 static変数
Q64 const と readonly の違い 定数の種類
Q65 プロパティでバリデーション カスタムプロパティ
Q66 base を使った共通処理+拡張 base キーワード
Q67 sealed override 継承制御
Q68 record の値等価 record型
Q69 クラスの参照等価 vs レコードの値等価 等価性の違い
Q70 演算子オーバーロード(Vec2 +) 演算子オーバーロード

Q51. Person.Name

解答例
class Person 
{ 
    public string Name { get; set; } = ""; 
}

var p = new Person { Name = "Taro" }; 
Console.WriteLine(p.Name);

Q52. 必須コンストラクタ

解答例
class Person
{ 
    public string Name { get; } 
    public Person(string name) => Name = name; 
}

Console.WriteLine(new Person("Hanako").Name);

Q53. カプセル化(privateフィールド)

解答例
class Counter
{ 
    private int _value; 
    public int Value => _value; 
    public void Inc() => _value++; 
}

var c = new Counter(); 
c.Inc(); 
Console.WriteLine(c.Value);

Q54. 自動実装プロパティ初期値

解答例
class Config
{ 
    public int Port { get; set; } = 8080; 
}

Console.WriteLine(new Config().Port);

Q55. 読み取り専用プロパティ + 面積

解答例
class Circle
{ 
    public double R { get; } 
    public double Area => Math.PI * R * R; 
    public Circle(double r) => R = r; 
}

Console.WriteLine(new Circle(2).Area);

Q56. init 専用プロパティ

解答例
class User
{ 
    public string Name { get; init; } = ""; 
    public int Age { get; init; } 
}

var u = new User { Name = "Mika", Age = 20 }; 
Console.WriteLine($"{u.Name},{u.Age}");

Q57. ToString オーバーライド

解答例
class Point
{ 
    public int X { get; set; } 
    public int Y { get; set; } 
    public override string ToString() => $"({X},{Y})"; 
}

Console.WriteLine(new Point { X = 3, Y = 4 });

Q58. 継承と override

解答例
class Animal
{ 
    public virtual void Speak() => Console.WriteLine("..."); 
}

class Dog : Animal
{ 
    public override void Speak() => Console.WriteLine("ワン!"); 
}

new Dog().Speak();

Q59. 抽象クラス

解答例
abstract class Shape
{ 
    public abstract double Area(); 
}

class Circle : Shape
{ 
    public double R { get; } 
    public Circle(double r) => R = r; 
    public override double Area() => Math.PI * R * R; 
}

Console.WriteLine(new Circle(2).Area);

Q60. インターフェース

解答例
interface IRunnable
{ 
    void Run(); 
}

class Runner : IRunnable
{ 
    public void Run() => Console.WriteLine("Running"); 
}

((IRunnable)new Runner()).Run();

Q61. 明示的インターフェース実装

解答例
interface IA { void Do(); } 
interface IB { void Do(); }

class Impl : IA, IB
{ 
    void IA.Do() => Console.WriteLine("IA"); 
    void IB.Do() => Console.WriteLine("IB"); 
}

var o = new Impl(); 
((IA)o).Do(); 
((IB)o).Do();

Q62. sealed クラス

解答例
class Base { } 
sealed class Mid : Base { } 
// class Leaf : Mid { } // ← コンパイルエラー

Console.WriteLine("OK");

Q63. 静的メンバーでインスタンス数

解答例
class Foo
{ 
    public static int Count { get; private set; } 
    public Foo() => Count++; 
}

new Foo(); 
new Foo(); 
Console.WriteLine(Foo.Count);

Q64. const と readonly の違い

解答例
class Sample
{ 
    public const int C = 10;
    public readonly int R; 
    public Sample(int x) => R = x; 
}

Console.WriteLine($"{Sample.C},{new Sample(123).R}");

Q65. プロパティでバリデーション

解答例
class Person
{ 
    int _age; 
    public int Age
    { 
        get => _age; 
        set
        { 
            if (value < 0) 
                throw new ArgumentOutOfRangeException(); 
            _age = value; 
        } 
    } 
}

var p = new Person(); 
p.Age = 10; 
Console.WriteLine(p.Age);

Q66. base を使った共通処理+拡張

解答例
class Logger
{ 
    public virtual void Log(string m) => Console.WriteLine($"[Base]{m}"); 
}

class TimeLogger : Logger
{ 
    public override void Log(string m) => 
        base.Log($"{DateTime.Now:HH:mm:ss} {m}"); 
}

new TimeLogger().Log("Hello");

Q67. sealed override

解答例
class A
{ 
    public virtual void Do() => Console.WriteLine("A"); 
}

class B : A
{ 
    public sealed override void Do() => Console.WriteLine("B"); 
}

class C : B
{ 
    // override不可 
}

new A().Do(); 
new B().Do(); 
new C().Do();

Q68. record の値等価

解答例
public record User(string Name, int Age);

Console.WriteLine(new User("Taro", 20) == new User("Taro", 20));

Q69. クラスの参照等価 vs レコードの値等価

解答例
class UC
{ 
    public string Name { get; } 
    public int Age { get; } 
    public UC(string n, int a) { Name = n; Age = a; } 
}

record UR(string Name, int Age);

Console.WriteLine(object.Equals(new UC("Taro", 20), new UC("Taro", 20))); // False
Console.WriteLine(new UR("Taro", 20) == new UR("Taro", 20));               // True

Q70. 演算子オーバーロード(Vec2 +)

解答例
struct Vec2
{ 
    public int X { get; } 
    public int Y { get; } 
    public Vec2(int x, int y) { X = x; Y = y; }
    
    public static Vec2 operator +(Vec2 a, Vec2 b) => 
        new(a.X + b.X, a.Y + b.Y);
    
    public override string ToString() => $"({X},{Y})";
}

Console.WriteLine(new Vec2(1, 2) + new Vec2(3, 4));

5. 例外処理とファイル操作

問題 内容 学習ポイント
Q71 0除算をキャッチ try-catch
Q72 finally は必ず実行 finally句
Q73 独自例外 カスタム例外
Q74 using で1行書き出し using文
Q75 行数カウント ファイル読み込み
Q76 数値行の合計(不正は無視) TryParse
Q77 ファイル存在確認 File.Exists
Q78 ディレクトリ作成→保存 Directory操作
Q79 追記 ファイル追記
Q80 コピー(上書き) ファイルコピー
Q81 移動(リネーム) ファイル移動
Q82 JSON シリアライズ JSON操作
Q83 JSON 読み込み JSON解析
Q84 XML 作成→読み込み XML操作
Q85 IDisposable を自作して using リソース管理

Q71. 0除算をキャッチ

解答例
try
{ 
    Console.WriteLine(10 / 0); 
}
catch (DivideByZeroException ex)
{ 
    Console.WriteLine("例外: " + ex.Message); 
}

Q72. finally は必ず実行

解答例
try
{ 
    Console.WriteLine("try"); 
    throw new InvalidOperationException(); 
}
catch
{ 
    Console.WriteLine("catch"); 
}
finally
{ 
    Console.WriteLine("finally"); 
}

Q73. 独自例外

解答例
class NegativeValueException : Exception
{ 
    public NegativeValueException(string message) : base(message) { } 
}

int value = -5; 
if (value < 0) 
    throw new NegativeValueException("負の値: " + value);

Q74. using で1行書き出し

解答例
using var sw = new StreamWriter("sample.txt", false);
sw.WriteLine("Hello, File!"); 
Console.WriteLine("書き込み完了");

Q75. 行数カウント

解答例
File.WriteAllLines("lines.txt", new[] { "a", "b", "c" });
Console.WriteLine(File.ReadAllLines("lines.txt").Length);

Q76. 数値行の合計(不正は無視)

解答例
File.WriteAllLines("nums.txt", new[] { "10", "20", "x", "30" });

int sum = 0; 
foreach (var line in File.ReadAllLines("nums.txt")) 
{
    if (int.TryParse(line, out var number)) 
        sum += number;
}

Console.WriteLine(sum); // 60

Q77. ファイル存在確認

解答例
File.WriteAllText("exists.txt", "ok");

Console.WriteLine(File.Exists("exists.txt"));  // True
Console.WriteLine(File.Exists("nope.txt"));    // False

Q78. ディレクトリ作成→保存

解答例
var dir = Path.Combine("data", "logs");
Directory.CreateDirectory(dir);

var path = Path.Combine(dir, "log.txt");
File.WriteAllText(path, $"created {DateTime.UtcNow:o}");

Console.WriteLine(path);

Q79. 追記

解答例
File.WriteAllText("append.txt", "line1\n");
File.AppendAllText("append.txt", "line2\n");

Console.WriteLine(File.ReadAllText("append.txt"));

Q80. コピー(上書き)

解答例
File.WriteAllText("src.txt", "copy me");
File.Copy("src.txt", "dst.txt", true);

Console.WriteLine(File.ReadAllText("dst.txt"));

Q81. 移動(リネーム)

解答例
File.WriteAllText("old.txt", "rename");
File.Move("old.txt", "new.txt", true);

Console.WriteLine(File.Exists("old.txt"));  // False
Console.WriteLine(File.Exists("new.txt"));  // True

Q82. JSON シリアライズ

解答例
using System.Text.Json;

var obj = new { Name = "Taro", Age = 20 };
var json = JsonSerializer.Serialize(obj, new JsonSerializerOptions 
{ 
    WriteIndented = true 
});

File.WriteAllText("user.json", json); 
Console.WriteLine(json);

Q83. JSON 読み込み

解答例
using System.Text.Json;

File.WriteAllText("user.json", """{ "Name":"Mika","Age":21 }""");

using var doc = JsonDocument.Parse(File.ReadAllText("user.json"));
var root = doc.RootElement;

Console.WriteLine(root.GetProperty("Name").GetString());
Console.WriteLine(root.GetProperty("Age").GetInt32());

Q84. XML 作成→読み込み

解答例
using System.Xml.Linq;

var xml = new XDocument(
    new XElement("Users",
        new XElement("User", 
            new XAttribute("id", 1), 
            new XElement("Name", "Taro"), 
            new XElement("Age", 20)
        ),
        new XElement("User", 
            new XAttribute("id", 2), 
            new XElement("Name", "Mika"), 
            new XElement("Age", 22)
        )
    )
);

xml.Save("users.xml");

var loaded = XDocument.Load("users.xml");
var user2 = loaded.Root!.Elements("User")
    .First(x => (int)x.Attribute("id")! == 2);

Console.WriteLine(user2.Element("Name")!.Value);

Q85. IDisposable を自作して using

解答例
class TempResource : IDisposable
{
    public void Use() => Console.WriteLine("Using resource");
    public void Dispose() => Console.WriteLine("Disposed");
}

using (var resource = new TempResource())
{ 
    resource.Use(); 
}

Console.WriteLine("スコープ終了後");

6. LINQ入門

問題 内容 学習ポイント
Q86 Where で偶数抽出 Where
Q87 Select で大文字化 Select
Q88 昇順/降順 OrderBy/OrderByDescending
Q89 長さでソート ソートキー指定
Q90 先頭文字で GroupBy GroupBy
Q91 SelectMany で直積 SelectMany
Q92 FirstOrDefault / Any / All 要素存在確認
Q93 集計 集計メソッド
Q94 Join で (UserName, DeptName) データ結合
Q95 Distinct / Union / Intersect / Except 集合演算

Q86. Where で偶数抽出

解答例
var numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
Console.WriteLine(string.Join(",", numbers.Where(n => n % 2 == 0)));

出力: 2,4,6

Q87. Select で大文字化

解答例
var words = new[] { "apple", "banana", "kiwi" };
Console.WriteLine(string.Join(",", words.Select(s => s.ToUpperInvariant())));

出力: APPLE,BANANA,KIWI

Q88. 昇順/降順

解答例
var nums = new[] { 5, 1, 4, 2, 3 };
Console.WriteLine(string.Join(",", nums.OrderBy(x => x)));
Console.WriteLine(string.Join(",", nums.OrderByDescending(x => x)));

出力:

1,2,3,4,5
5,4,3,2,1

Q89. 長さでソート

解答例
var words = new[] { "car", "strawberry", "tea", "melon" };
Console.WriteLine(string.Join(",", words.OrderBy(s => s.Length)));

出力: car,tea,melon,strawberry

Q90. 先頭文字で GroupBy

解答例
var items = new[] { "apple", "apricot", "banana", "blueberry", "cherry" };
foreach (var group in items.GroupBy(s => s[0])) 
{
    Console.WriteLine($"{group.Key}:{group.Count()}");
}

出力:

a:2
b:2
c:1

Q91. SelectMany で直積

解答例
var xs = new[] { 1, 2 }; 
var ys = new[] { 'A', 'B', 'C' };
Console.WriteLine(string.Join(" ", xs.SelectMany(x => ys, (x, y) => $"({x},{y})")));

出力: (1,A) (1,B) (1,C) (2,A) (2,B) (2,C)

Q92. FirstOrDefault / Any / All

解答例
var numbers = new[] { 2, 4, 6, 8 };
Console.WriteLine(numbers.FirstOrDefault(n => n > 5));  // 6
Console.WriteLine(numbers.Any(n => n % 3 == 0));        // False
Console.WriteLine(numbers.All(n => n % 2 == 0));        // True

Q93. 集計

解答例
var numbers = new[] { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers.Count());    // 5
Console.WriteLine(numbers.Sum());      // 15
Console.WriteLine(numbers.Average());  // 3
Console.WriteLine(numbers.Max());      // 5
Console.WriteLine(numbers.Min());      // 1

Q94. Join で (UserName, DeptName)

解答例
var users = new[]
{ 
    new { Id = 1, Name = "Taro", DeptId = 10 }, 
    new { Id = 2, Name = "Mika", DeptId = 20 }, 
    new { Id = 3, Name = "Ken", DeptId = 10 } 
};

var depts = new[]
{ 
    new { DeptId = 10, DeptName = "Sales" }, 
    new { DeptId = 20, DeptName = "Dev" } 
};

var query = users.Join(depts, 
    u => u.DeptId, 
    d => d.DeptId, 
    (u, d) => (u.Name, d.DeptName));

foreach (var x in query) 
{
    Console.WriteLine($"{x.Name} - {x.DeptName}");
}

出力:

Taro - Sales
Mika - Dev
Ken - Sales

Q95. Distinct / Union / Intersect / Except

解答例
var a = new[] { 1, 2, 2, 3 }; 
var b = new[] { 2, 3, 4 };

Console.WriteLine(string.Join(",", a.Distinct()));     // 1,2,3
Console.WriteLine(string.Join(",", a.Union(b)));       // 1,2,3,4
Console.WriteLine(string.Join(",", a.Intersect(b)));   // 2,3
Console.WriteLine(string.Join(",", a.Except(b)));      // 1

7. まとめ・発展

問題 内容 学習ポイント
Q96 現在時刻とUTC(Offsetも) 日時操作
Q97 2つの日時の差(TimeSpan) 時間差計算
Q98 Nullable と ?? / ?. null安全性
Q99 enum と switch式 enum型とswitch式
Q100 簡易電卓(a op b) 総合演習

Q96. 現在時刻とUTC(Offsetも)

解答例
Console.WriteLine($"Local: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
Console.WriteLine($"UTC  : {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}");
Console.WriteLine($"Offset: {DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss zzz}");

出力例:

Local: 2025-09-09 14:30:45
UTC  : 2025-09-09 05:30:45
Offset: 2025-09-09 14:30:45 +09:00

Q97. 2つの日時の差(TimeSpan)

解答例
var start = new DateTime(2025, 9, 1, 9, 30, 0);
var end = new DateTime(2025, 9, 1, 18, 15, 0);
Console.WriteLine((end - start).TotalHours);

出力: 8.75

Q98. Nullable と ?? / ?.

解答例
int? nullableInt = null; 
Console.WriteLine(nullableInt ?? -1);        // -1

string? nullableString = null; 
Console.WriteLine(nullableString?.Length ?? 0);  // 0

Q99. enum と switch式

解答例
enum Status { Ready, Running, Done, Error }

Status status = Status.Running;
Console.WriteLine(status switch
{ 
    Status.Ready => "準備OK", 
    Status.Running => "実行中", 
    Status.Done => "完了", 
    Status.Error => "エラー", 
    _ => "未知" 
});

出力: 実行中

Q100. 簡易電卓(a op b)

解答例
Console.Write("式 (例: 12 + 3): ");
var line = Console.ReadLine();

if (string.IsNullOrWhiteSpace(line)) 
{
    Console.WriteLine("入力なし");
}
else
{
    var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
    
    if (parts.Length == 3 && 
        double.TryParse(parts[0], out double a) && 
        double.TryParse(parts[2], out double b))
    {
        string op = parts[1];
        double result = op switch
        { 
            "+" => a + b, 
            "-" => a - b, 
            "*" => a * b, 
            "/" => b != 0 ? a / b : double.NaN, 
            _ => double.NaN 
        };
        
        Console.WriteLine($"= {result}");
    } 
    else 
    {
        Console.WriteLine("形式が不正(例: 12 + 3)");
    }
}

使用例:

式 (例: 12 + 3): 15.5 * 2
= 31

🎓 100問完走おめでとうございます!

ここまで完走できれば、C#基礎の主要トピックを一巡できています。

長くてごめんなさい。
お疲れさまでした!!

学習リソース

公式ドキュメント

20
26
2

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
20
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?