using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleAppDataTableJoinByLinq
{
// 結合後の結果を格納するためのクラス定義
public class Result
{
public int OrderID { get; set; }
public string CompanyName { get; set; }
public int? EmployeeID { set; get; }
public DateTime? OrderDate { get; set; }
public decimal? Freight { get; set; }
}
class Program
{
static void Main(string[] args)
{
string connString = @"data source=lpc:(local)\sqlexpress;initial catalog=NORTHWIND;integrated security=True;";
string queryOrders = "SELECT [OrderID],[CustomerID],[EmployeeID],[OrderDate],[RequiredDate],[ShippedDate],[ShipVia],[Freight],[ShipName],[ShipAddress],[ShipCity],[ShipRegion],[ShipPostalCode],[ShipCountry] FROM [Orders]";
string queryCustomers = "SELECT [CustomerID],[CompanyName],[ContactName],[ContactTitle],[Address],[City],[Region],[PostalCode],[Country],[Phone],[Fax] FROM [Customers]";
DataTable orders = new DataTable();
DataTable customers = new DataTable();
using (SqlConnection connection = new SqlConnection(connString))
{
using (SqlCommand command = new SqlCommand(queryOrders, connection))
{
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(orders);
}
using (SqlCommand command = new SqlCommand(queryCustomers, connection))
{
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(customers);
}
}
// 内部結合
var innerJoin = from o in orders.AsEnumerable()
join c in customers.AsEnumerable()
on o.Field<string>("CustomerID") equals c.Field<string>("CustomerID")
where o.Field<int?>("EmployeeID") == 9
select new Result
{
OrderID = o.Field<int>("OrderID"),
CompanyName = c.Field<string>("CompanyName"),
EmployeeID = o.Field<int?>("EmployeeID"),
OrderDate = o.Field<DateTime?>("OrderDate"),
Freight = o.Field<decimal?>("Freight")
};
foreach (Result result in innerJoin)
{
Console.WriteLine($"Id: {result.OrderID}, Name: {result.CompanyName}, EmpID: {result.EmployeeID}, Date: {result.OrderDate}, Freight: {result.Freight}");
}
Console.WriteLine("--------------------------------");
// 左外部結合
var leftOuterJoin = from o in orders.AsEnumerable()
join c in customers.AsEnumerable()
on o.Field<string>("CustomerID") equals c.Field<string>("CustomerID") into cGroup
from item in cGroup.DefaultIfEmpty() // Empty だと item が null になる
where o.Field<int?>("EmployeeID") == 9
select new Result
{
OrderID = o.Field<int>("OrderID"),
CompanyName = (item == null) ? "N/A" : item.Field<string>("CompanyName"), // item.Field<string>("CompanyName") ?? "N/A" ではだめ
EmployeeID = o.Field<int?>("EmployeeID"),
OrderDate = o.Field<DateTime?>("OrderDate"),
Freight = o.Field<decimal?>("Freight")
};
foreach (Result result in leftOuterJoin)
{
Console.WriteLine($"Id: {result.OrderID}, Name: {result.CompanyName}, EmpID: {result.EmployeeID}, Date: {result.OrderDate}, Freight: {result.Freight}");
}
}
}
}