加入运营

两个数据源的连接是一个数据源中的对象与另一个数据源中共享公共属性的对象的关联。

加入

基于键选择器函数连接两个序列并提取值对。

方法语法

// 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 |