「東雲 忠太郎」の平凡な日常のできごと

「東雲 忠太郎」の平凡な日常のできごと

2025.08.16
XML
カテゴリ: LINQ


using System;

using System.Data;

using System.Linq;



{

    static void Main()

    {

        // 生徒マスタ

        DataTable students = new DataTable();

        students.Columns.Add("Id", typeof(int));

        students.Columns.Add("Name", typeof(string));


        students.Rows.Add(1, "山田");

        students.Rows.Add(2, "佐藤");

        students.Rows.Add(3, "鈴木");


        // 成績マスタ

        DataTable scores = new DataTable();

        scores.Columns.Add("StudentId", typeof(int));

        scores.Columns.Add("Points", typeof(int));


        scores.Rows.Add(1, 80);

        scores.Rows.Add(3, 70);


        // GroupJoin + SelectMany で外部結合

        var query = students.AsEnumerable()

            .GroupJoin(

                scores.AsEnumerable(),

                s => s.Field<int>("Id"),

                sc => sc.Field<int>("StudentId"),

                (s, scGroup) => new { Student = s, Scores = scGroup.DefaultIfEmpty() }

            )

            .SelectMany(

                x => x.Scores,

                (x, sc) => new

                {

                    StudentName = x.Student.Field<string>("Name"),

                    Points = sc != null ? sc.Field<int>("Points") : (int?)null

                }

            );


        // 出力

        foreach (var item in query)

        {

            Console.WriteLine($"{item.StudentName}: {(item.Points.HasValue ? item.Points.Value.ToString() : "未採点")}");

        }

    }

}







お気に入りの記事を「いいね!」で応援しよう

Last updated  2025.08.16 14:04:25


【毎日開催】
15記事にいいね!で1ポイント
10秒滞在
いいね! -- / --
おめでとうございます!
ミッションを達成しました。
※「ポイントを獲得する」ボタンを押すと広告が表示されます。
x
X

© Rakuten Group, Inc.
X
Design a Mobile Site
スマートフォン版を閲覧 | PC版を閲覧
Share by: