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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class Program
  6. {
  7. static void Main()
  8. {
  9. // 模拟两个表的数据
  10. List<Table1> table1Data = new List<Table1>
  11. {
  12. new Table1 { Id = 1, CommonField = "A", Value = "Value1" },
  13. new Table1 { Id = 2, CommonField = "B", Value = "Value2" },
  14. new Table1 { Id = 3, CommonField = "C", Value = "Value3" }
  15. };
  16.  
  17. List<Table2> table2Data = new List<Table2>
  18. {
  19. new Table2 { Id = 101, CommonField = "A", Description = "Desc1" },
  20. new Table2 { Id = 102, CommonField = "B", Description = "Desc2" },
  21. new Table2 { Id = 103, CommonField = "D", Description = "Desc3" }
  22. };
  23.  
  24. // 使用 LINQ 进行连接操作
  25. var query = from t1 in table1Data
  26. join t2 in table2Data on t1.CommonField equals t2.CommonField
  27. select new { t1.Id, t1.CommonField, t1.Value, t2.Description };
  28.  
  29. // 打印结果
  30. foreach (var result in query)
  31. {
  32. Console.WriteLine($"{result.Id} - {result.CommonField} - {result.Value} - {result.Description}");
  33. }
  34. }
  35. }
  36.  
  37. // 定义两个表的类
  38. class Table1
  39. {
  40. public int Id { get; set; }
  41. public string CommonField { get; set; }
  42. public string Value { get; set; }
  43. }
  44.  
  45. class Table2
  46. {
  47. public int Id { get; set; }
  48. public string CommonField { get; set; }
  49. public string Description { get; set; }
  50. }
  51.  
  52.  

留言

這個網誌中的熱門文章

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

Oracle 工作排程 DBMS_JOB 筆記

Oracle 例外控制(Exception Control)