C#, LINQ, 2個Table Join 使用1個欄位條件Join

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // 模拟两个表的数据
        List<Table1> table1Data = new List<Table1>
        {
            new Table1 { Id = 1, CommonField = "A", Value = "Value1" },
            new Table1 { Id = 2, CommonField = "B", Value = "Value2" },
            new Table1 { Id = 3, CommonField = "C", Value = "Value3" }
        };

        List<Table2> table2Data = new List<Table2>
        {
            new Table2 { Id = 101, CommonField = "A", Description = "Desc1" },
            new Table2 { Id = 102, CommonField = "B", Description = "Desc2" },
            new Table2 { Id = 103, CommonField = "D", Description = "Desc3" }
        };

        // 使用 LINQ 进行连接操作
        var query = from t1 in table1Data
                    join t2 in table2Data on t1.CommonField equals t2.CommonField
                    select new { t1.Id, t1.CommonField, t1.Value, t2.Description };

        // 打印结果
        foreach (var result in query)
        {
            Console.WriteLine($"{result.Id} - {result.CommonField} - {result.Value} - {result.Description}");
        }
    }
}

// 定义两个表的类
class Table1
{
    public int Id { get; set; }
    public string CommonField { get; set; }
    public string Value { get; set; }
}

class Table2
{
    public int Id { get; set; }
    public string CommonField { get; set; }
    public string Description { get; set; }
}


留言

這個網誌中的熱門文章

ORA-12514: TNS: 監聽器目前不知道連線描述區中要求的服務

Oracle 例外控制(Exception Control)

Oracle 工作排程 DBMS_JOB 筆記