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

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

2024.02.25
XML
カテゴリ: LINQ


using System;

using System.Data;

using System.Linq;


class Program

{

    static void Main(string[] args)

    {

        // サンプルのDataTable1を作成します

        DataTable table1 = new DataTable();

        table1.Columns.Add("ID", typeof(int));

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

        table1.Rows.Add(1, "John");

        table1.Rows.Add(2, "Alice");

        table1.Rows.Add(3, "Bob");


        // サンプルのDataTable2を作成します

        DataTable table2 = new DataTable();

        table2.Columns.Add("ID", typeof(int));

        table2.Columns.Add("Age", typeof(int));

        table2.Rows.Add(1, 30);

        table2.Rows.Add(3, 25);

        table2.Rows.Add(4, 35);


        // 外部結合を行います

        var query = from row1 in table1.AsEnumerable()

                    join row2 in table2.AsEnumerable() on row1.Field<int>("ID") equals row2.Field<int>("ID") into temp

                    from t in temp.DefaultIfEmpty()

                    select new

                    {

                        ID = row1.Field<int>("ID"),

                        Name = row1.Field<string>("Name"),

                        Age = t?.Field<int>("Age") // null条件演算子を使用してnullの場合にnullを返すようにします

                    };


        // 結果を出力します

        foreach (var item in query)

        {

            Console.WriteLine($"ID: {item.ID}, Name: {item.Name}, Age: {(item.Age != null ? item.Age.ToString() : "N/A")}");

        }

    }

}







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

Last updated  2024.02.25 07:28:53


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

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