C#, LINQ, 2個Table Join 使用2個欄位條件Join
2個Table Join 使用2個欄位條件Join
範例1:
- join的欄位名稱要相同
範例1:
範例2:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class Program
- {
- static void Main()
- {
- // 假设有两个表格
- List<Table1> table1Data = new List<Table1>
- {
- new Table1 { ID = 1, Name = "John" },
- new Table1 { ID = 2, Name = "Alice" },
- new Table1 { ID = 3, Name = "Bob" }
- };
- List<Table2> table2Data = new List<Table2>
- {
- new Table2 { ID = 1, Age = 25 },
- new Table2 { ID = 2, Age = 30 },
- new Table2 { ID = 3, Age = 28 }
- };
- // 使用 LINQ 进行两个表格的连接
- var query = from t1 in table1Data
- join t2 in table2Data on new { t1.ID, t1.Name } equals new { t2.ID, Name = "John" }
- select new { t1.ID, t1.Name, t2.Age };
- // 打印结果
- foreach (var result in query)
- {
- Console.WriteLine($"ID: {result.ID}, Name: {result.Name}, Age: {result.Age}");
- }
- }
- }
- // 表格1
- class Table1
- {
- public int ID { get; set; }
- public string Name { get; set; }
- }
- // 表格2
- class Table2
- {
- public int ID { get; set; }
- public int Age { get; set; }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class Program
- {
- static void Main()
- {
- // 建立一些示例資料
- List<Person> persons = new List<Person>
- {
- new Person { PersonId = 1, Name = "John", Age = 25 },
- new Person { PersonId = 2, Name = "Jane", Age = 30 },
- new Person { PersonId = 3, Name = "Bob", Age = 28 }
- };
- List<Contact> contacts = new List<Contact>
- {
- new Contact { PersonId = 1, Name = "John", Email = "john@example.com" },
- new Contact { PersonId = 2, Name = "Jane", Email = "jane@example.com" },
- new Contact { PersonId = 3, Name = "Bob", Email = "bob@example.com" }
- };
- // 使用 LINQ 進行兩個表格的聯結
- var query = from person in persons
- join contact in contacts
- on new { person.PersonId, person.Name } equals new { contact.PersonId, Name = contact.Name }
- select new
- {
- person.PersonId,
- person.Name,
- person.Age,
- contact.Email
- };
- // 輸出結果
- foreach (var result in query)
- {
- Console.WriteLine($"{result.PersonId} - {result.Name}, Age: {result.Age}, Email: {result.Email}");
- }
- }
- }
- // 定義 Person 類別
- class Person
- {
- public int PersonId { get; set; }
- public string Name { get; set; }
- public int Age { get; set; }
- }
- // 定義 Contact 類別
- class Contact
- {
- public int PersonId { get; set; }
- public string Name { get; set; }
- public string Email { get; set; }
- }
留言
張貼留言