加入運營

兩個資料來源的連線是一個資料來源中的物件與另一個資料來源中共享公共屬性的物件的關聯。

加入

基於鍵選擇器函式連線兩個序列並提取值對。

方法語法

// Join

class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Order
{
    public string Description { get; set; }
    public int CustomerId { get; set; }
}
...

var customers = new Customer[] 
{
    new Customer { Id = 1, Name = "C1" },
    new Customer { Id = 2, Name = "C2" },
    new Customer { Id = 3, Name = "C3" }
};

var orders = new Order[]
{
    new Order { Description = "O1", CustomerId = 1 },
    new Order { Description = "O2", CustomerId = 1 },
    new Order { Description = "O3", CustomerId = 2 },
    new Order { Description = "O4", CustomerId = 3 },
};

var join = customers.Join(orders, c => c.Id, o => o.CustomerId, (c, o) => c.Name + "-" + o.Description);

// join = { "C1-O1", "C1-O2", "C2-O3", "C3-O4" }

查詢語法

// join … in … on … equals …

var join = from c in customers
           join o in orders
           on c.Id equals o.CustomerId
           select o.Description + "-" + c.Name;

// join = { "O1-C1", "O2-C1", "O3-C2", "O4-C3" }

群組加入

基於鍵選擇器函式連線兩個序列,並將每個元素的結果匹配分組。

方法語法

// GroupJoin

var groupJoin = customers.GroupJoin(orders,
                                    c => c.Id, 
                                    o => o.CustomerId, 
                                    (c, ors) => c.Name + "-" + string.Join(",", ors.Select(o => o.Description)));

// groupJoin = { "C1-O1,O2", "C2-O3", "C3-O4" }

查詢語法

// join … in … on … equals … into …

var groupJoin = from c in customers
                join o in orders               
                on c.Id equals o.CustomerId
                into customerOrders
                select string.Join(",", customerOrders.Select(o => o.Description)) + "-" + c.Name;

// groupJoin = { "O1,O2-C1", "O3-C2", "O4-C3" }

壓縮

將指定的函式應用於兩個序列的相應元素,生成一系列結果。

var numbers = new [] { 1, 2, 3, 4, 5, 6 };
var words = new [] { "one", "two", "three" };

var numbersWithWords =
    numbers
    .Zip(
        words,
        (number, word) => new { number, word });

// Results

//| number | word   |
//| ------ | ------ |
//| 1      |  one   |
//| 2      |  two   |
//| 3      |  three |