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

2個Table Join 使用2個欄位條件Join
  • join的欄位名稱要相同


範例1:

  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, Name = "John" },
  13. new Table1 { ID = 2, Name = "Alice" },
  14. new Table1 { ID = 3, Name = "Bob" }
  15. };
  16.  
  17. List<Table2> table2Data = new List<Table2>
  18. {
  19. new Table2 { ID = 1, Age = 25 },
  20. new Table2 { ID = 2, Age = 30 },
  21. new Table2 { ID = 3, Age = 28 }
  22. };
  23.  
  24. // 使用 LINQ 进行两个表格的连接
  25. var query = from t1 in table1Data
  26. join t2 in table2Data on new { t1.ID, t1.Name } equals new { t2.ID, Name = "John" }
  27. select new { t1.ID, t1.Name, t2.Age };
  28.  
  29. // 打印结果
  30. foreach (var result in query)
  31. {
  32. Console.WriteLine($"ID: {result.ID}, Name: {result.Name}, Age: {result.Age}");
  33. }
  34. }
  35. }
  36.  
  37. // 表格1
  38. class Table1
  39. {
  40. public int ID { get; set; }
  41. public string Name { get; set; }
  42. }
  43.  
  44. // 表格2
  45. class Table2
  46. {
  47. public int ID { get; set; }
  48. public int Age { get; set; }
  49. }

範例2:

  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<Person> persons = new List<Person>
  11. {
  12. new Person { PersonId = 1, Name = "John", Age = 25 },
  13. new Person { PersonId = 2, Name = "Jane", Age = 30 },
  14. new Person { PersonId = 3, Name = "Bob", Age = 28 }
  15. };
  16.  
  17. List<Contact> contacts = new List<Contact>
  18. {
  19. new Contact { PersonId = 1, Name = "John", Email = "john@example.com" },
  20. new Contact { PersonId = 2, Name = "Jane", Email = "jane@example.com" },
  21. new Contact { PersonId = 3, Name = "Bob", Email = "bob@example.com" }
  22. };
  23.  
  24. // 使用 LINQ 進行兩個表格的聯結
  25. var query = from person in persons
  26. join contact in contacts
  27. on new { person.PersonId, person.Name } equals new { contact.PersonId, Name = contact.Name }
  28. select new
  29. {
  30. person.PersonId,
  31. person.Name,
  32. person.Age,
  33. contact.Email
  34. };
  35.  
  36. // 輸出結果
  37. foreach (var result in query)
  38. {
  39. Console.WriteLine($"{result.PersonId} - {result.Name}, Age: {result.Age}, Email: {result.Email}");
  40. }
  41. }
  42. }
  43.  
  44. // 定義 Person 類別
  45. class Person
  46. {
  47. public int PersonId { get; set; }
  48. public string Name { get; set; }
  49. public int Age { get; set; }
  50. }
  51.  
  52. // 定義 Contact 類別
  53. class Contact
  54. {
  55. public int PersonId { get; set; }
  56. public string Name { get; set; }
  57. public string Email { get; set; }
  58. }

留言

這個網誌中的熱門文章

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

Oracle 工作排程 DBMS_JOB 筆記

Oracle 例外控制(Exception Control)