動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About

動くコード図鑑

$ ls -1 /library | wc -l → 619

触って動く、検証済みの正解集。

公開記事から抽出した全コードブロックを 1 つずつページ化。 ▶ ボタンで 実行ログを再生し、 さも今動いてるかのように出力を流す。

この図鑑の使い方

言語で絞る

C# / SQL / TypeScript / PowerShell / Bash でフィルタ。

▶ で実行

事前収録の出力を 1 行ずつ再生。 ぱっと結果が見える。

記事と接続

各 snippet は出典記事へのリンク付き。 文脈ごと読める。

絞り込み

snippet 一覧

473
C#
using System.Linq;

var ids = new List<int> { 1, 2, 2, 3, 3, 3, 4 };
var unique = ids.Distinct().ToList();
//結果: [1, 2, 3, 4]

パターン1: Distinct ──単純な重複を1行で潰す

C# でリストの重複を一意にする3つの書き方(Distinct / GroupBy / HashSet)未収録#d46d933644a6
C#
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}
▶ 実行可

罠:参照型のリストでDistinctは動かない

C# でリストの重複を一意にする3つの書き方(Distinct / GroupBy / HashSet)#45edb7bbd5f0
C#
//対処A: IEqualityComparer<T>を渡す
public class CustomerComparer : IEqualityComparer<Customer>
{
    public bool Equals(Customer x, Customer y)=>
        x?.Id == y?.Id && x?.Name == y?.Name;

罠:参照型のリストでDistinctは動かない

C# でリストの重複を一意にする3つの書き方(Distinct / GroupBy / HashSet)未収録#8249db6f6321
C#
//対処B:クラス側でIEquatable<Customer>を実装
public class Customer : IEquatable<Customer>
{
    public int Id { get; set; }
    public string Name { get; set; }

罠:参照型のリストでDistinctは動かない

C# でリストの重複を一意にする3つの書き方(Distinct / GroupBy / HashSet)未収録#47f2125f4dac
C#
var customers = new List<Customer>
{
    new Customer { Id = 1, Name = "田中", UpdatedAt = new DateTime(2025, 1, 10)},
    new Customer { Id = 1, Name = "田中(旧)", UpdatedAt = new DateTime(2024, 6, 1)},
    new Customer { Id = 2, Name = "山田", UpdatedAt = new DateTime(2025, 2, 5)},

パターン2: GroupBy + Select ──キーで一意にする業務系の定番

C# でリストの重複を一意にする3つの書き方(Distinct / GroupBy / HashSet)未収録#22180cc0d40e
C#
//顧客ID +取引日で一意にする
var unique = transactions
    .GroupBy(t => new { t.CustomerId, t.TransactionDate })
    .Select(g => g.First())
    .ToList();

複合キーで一意にしたい時

C# でリストの重複を一意にする3つの書き方(Distinct / GroupBy / HashSet)未収録#d839385e04d1
C#
//単純な重複排除
var ids = new List<int> { 1, 2, 2, 3, 3, 3, 4 };
var unique = new HashSet<int>(ids).ToList();
//結果: [1, 2, 3, 4]

パターン3: HashSet<T> ──大量データ・重複検知に使う

C# でリストの重複を一意にする3つの書き方(Distinct / GroupBy / HashSet)未収録#870822b31320
C#
var emails = new List<string> { "Foo@example.com", "foo@example.com", "Bar@example.com" };
var unique = new HashSet<string>(emails, StringComparer.OrdinalIgnoreCase).ToList();
//結果: ["Foo@example.com", "Bar@example.com"]

パターン3: HashSet<T> ──大量データ・重複検知に使う

C# でリストの重複を一意にする3つの書き方(Distinct / GroupBy / HashSet)未収録#e2a378f37c27
C#
var seen = new HashSet<int>();
foreach (var id in inputIds)
{
    if (!seen.Add(id))
    {
▶ 実行可

パターン3: HashSet<T> ──大量データ・重複検知に使う

C# でリストの重複を一意にする3つの書き方(Distinct / GroupBy / HashSet)#c988968a2a28
C#
var list = new List<string> { "a", null, "b", null, "c" };
var unique = list.Distinct().ToList();
//結果: ["a", null, "b", "c"]  ← nullが1個残る

nullを含むリストでの挙動

C# でリストの重複を一意にする3つの書き方(Distinct / GroupBy / HashSet)未収録#bbe47862b7fa
C#
// C# 9+レコード型
public record Customer(int Id, string Name);

var customers = new List<Customer>
{

モダンC#の補足

C# でリストの重複を一意にする3つの書き方(Distinct / GroupBy / HashSet)未収録#ca8aeb4289c0
C#
// ✅定石1:最小シリアライズ・デシリアライズ
using Newtonsoft.Json;

public class OrderDto
{
▶ 実行可

定石1: NuGetでNewtonsoft.Jsonを入れる+最小コード

C# Newtonsoft.Json で業務系JSON処理を実戦投入する完全ガイド(.NET Framework 4.7.2 編)#ebd2150a39f0
C#
// ✅定石2:業務系ベース設定(プロジェクト全体で使い回す)
public static class JsonConfig
{
    public static readonly JsonSerializerSettings BusinessDefault = new JsonSerializerSettings
    {

定石2: JsonSerializerSettingsで業務系ベース設定を固定

C# Newtonsoft.Json で業務系JSON処理を実戦投入する完全ガイド(.NET Framework 4.7.2 編)未収録#724e2bb51ad5
C#
// ❌ NG:既定設定でKind=Localをシリアライズすると、ローカル時刻が出力される
var bad = new { CreatedAt = DateTime.Now };  // Kind=Local
string badJson = JsonConvert.SerializeObject(bad);
// → {"CreatedAt":"2026-05-09T14:00:00+09:00"}  ← JST環境のローカル時刻

定石3: DateTimeのUTC統一で時刻ズレを潰す

C# Newtonsoft.Json で業務系JSON処理を実戦投入する完全ガイド(.NET Framework 4.7.2 編)未収録#4610d44165e1
C#
// ✅定石4:金額用カスタムJsonConverter(書き出し時に円マーク付与など)
public class MoneyJsonConverter : JsonConverter<decimal>
{
    public override void WriteJson(JsonWriter writer, decimal value, JsonSerializer serializer)
    {

定石4:カスタムJsonConverter —業務固有型の専用変換

C# Newtonsoft.Json で業務系JSON処理を実戦投入する完全ガイド(.NET Framework 4.7.2 編)未収録#90fd64ac232b
C#
// ✅定石5: JsonTextReaderで巨大JSONをストリーミング読み込み
using (var fs = new FileStream(jsonFilePath, FileMode.Open, FileAccess.Read))
using (var sr = new StreamReader(fs))
using (var reader = new JsonTextReader(sr))
{

定石5: JsonTextReaderでストリーミング読み込み

C# Newtonsoft.Json で業務系JSON処理を実戦投入する完全ガイド(.NET Framework 4.7.2 編)未収録#15abeba39934
C#
// ❌ NG: JObject経由でdouble化け(金額計算が事故る)
string apiResponse = "{\"amount\": 12500.10}";
var jobj = Newtonsoft.Json.Linq.JObject.Parse(apiResponse);

double amountDouble = (double)jobj["amount"];   // 12500.099999999...の罠

定石6: decimalがdoubleに化ける問題と対策

C# Newtonsoft.Json で業務系JSON処理を実戦投入する完全ガイド(.NET Framework 4.7.2 編)未収録#4e944e9ff5db
C#
//多くの人がこう書いてる(俺も最初これだった)
private void btnImport_Click(object sender, EventArgs e)
{
    using (var ofd = new OpenFileDialog())
    {

private void btnImport_Click(object sender, EventArgs e)

C# OpenFileDialog をフォームのフィールドにする時の正しい書き方未収録#bba803994efe
C#
private void btnImport_Click(object sender, EventArgs e)
{
    using (var ofd = new OpenFileDialog())
    {
        ofd.Title = "取り込みファイルを選択";

ローカルusing版(基本パターン)

C# OpenFileDialog をフォームのフィールドにする時の正しい書き方未収録#a50deba795dc
C#
public partial class ImportForm : Form
{
    private readonly OpenFileDialog _csvOfd;

    public ImportForm()

フィールド化版(コンストラクタ初期化+ Form.Dispose連動)

C# OpenFileDialog をフォームのフィールドにする時の正しい書き方未収録#95165e179d30
C#
// Designer配置済みopenFileDialog1をクリックハンドラから使う
private void btnImport_Click(object sender, EventArgs e)
{
    if (this.openFileDialog1.ShowDialog(this)== DialogResult.OK)
    {

フィールド化+ Designer配置版(別解)

C# OpenFileDialog をフォームのフィールドにする時の正しい書き方未収録#3d4abf12c310
C#
//インスタンスを使い回せば、前回フォルダから自動で開く
if (_csvOfd.ShowDialog(this)== DialogResult.OK)
{
    // ...取り込み処理...
}

①前回開いたフォルダの自動記憶

C# OpenFileDialog をフォームのフィールドにする時の正しい書き方未収録#6a9c418cc3d7
C#
public static class DialogFactory
{
    public static OpenFileDialog CreateCsvOpenDialog()
    {
        return new OpenFileDialog

② Filterプリセットを画面間で統一

C# OpenFileDialog をフォームのフィールドにする時の正しい書き方未収録#918442e2d423
C#
// ❌ NG:毎回InitialDirectoryを上書き→記憶効果ゼロ
private void btnImport_Click(object sender, EventArgs e)
{
    _csvOfd.InitialDirectory = @"C:\Import";   // ←これが入ってると毎回ここから始まる
    if (_csvOfd.ShowDialog(this)== DialogResult.OK){ ... }

① InitialDirectoryを毎回上書きしてて記憶効果ゼロ

C# OpenFileDialog をフォームのフィールドにする時の正しい書き方未収録#bd75157be9cc
C#
// ❌ NG: ChildFormをShowしたまま参照を残す→ ChildForm.DisposeされずOpenFileDialogも残る
appWideManager.OpenChild(new ChildForm());   //内部でList<Form>に保持

// ✅ OK: ChildFormのFormClosedで参照を切る
var child = new ChildForm();

② Form.Disposeされない子フォームでメモリリーク

C# OpenFileDialog をフォームのフィールドにする時の正しい書き方未収録#ca78fe3151fb
C#
// ❌ NG: Designerのデフォルト名のまま
this.openFileDialog1.ShowDialog(this);   // CSV用?画像用?
this.openFileDialog2.ShowDialog(this);

// ✅ OK: DesignerのプロパティウィンドウでNameを意味付け

③ Designer配置時のComponent名衝突

C# OpenFileDialog をフォームのフィールドにする時の正しい書き方未収録#1006210be5cd
C#
public interface IFileSelector
{
    string SelectFile(string filter, string initialDirectory);
}

Q2.フィールド化したOpenFileDialogのテストは書きづらくない?

C# OpenFileDialog をフォームのフィールドにする時の正しい書き方未収録#d2666a62ada8
C#
_csvOfd.Multiselect = true;
if (_csvOfd.ShowDialog(this)== DialogResult.OK)
{
    foreach (string path in _csvOfd.FileNames)
    {

Q4. Multiselect = trueで複数選択したファイルはどう取れる?

C# OpenFileDialog をフォームのフィールドにする時の正しい書き方未収録#85450a466c91
C#
using System;
using System.IO;
using System.Windows.Forms;

namespace CustomOpenFileDialog

実際にCustomOpenFileDialogを作ってみる。

C#でOpenFileDialogが継承できない?それならフィールドに持っちゃえばいいんじゃね?未収録#8467efcda984
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

実際にCustomOpenFileDialogを作ってみる。

C#でOpenFileDialogが継承できない?それならフィールドに持っちゃえばいいんじゃね?未収録#cfb43496e568