📜  LINQ交叉加入(1)

📅  最后修改于: 2023-12-03 15:17:20.029000             🧑  作者: Mango

LINQ交叉加入介绍

在LINQ中,使用交叉加入操作符Join可以将两个序列中的元素进行组合,而交叉加入操作符CrossJoin则可以将两个序列中的所有元素进行组合。本篇文章将介绍如何使用LINQ的交叉加入操作符。

Join操作符

Join操作符用于将两个序列中满足特定条件的元素组合。它的语法为:

Join<TOuter, TInner, TKey, TResult>(IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector)

该方法有五个参数:

  • outer:需要查询的第一个序列(左表)。
  • inner:需要查询的第二个序列(右表)。
  • outerKeySelector:用于左表中元素提取关键字的函数。
  • innerKeySelector:用于右表中元素提取关键字的函数。
  • resultSelector:用于组合两个序列中满足条件的元素的函数。

使用示例:

var orders = new List<Order>
{
    new Order { OrderId = 1, OrderDate = DateTime.Parse("2019-01-01"), CustomerId = 1 },
    new Order { OrderId = 2, OrderDate = DateTime.Parse("2019-01-02"), CustomerId = 2 },
    new Order { OrderId = 3, OrderDate = DateTime.Parse("2019-01-03"), CustomerId = 1 },
};

var customers = new List<Customer>
{
    new Customer { CustomerId = 1, CustomerName = "Alice" },
    new Customer { CustomerId = 2, CustomerName = "Bob" },
};

var query = from order in orders
            join customer in customers on order.CustomerId equals customer.CustomerId
            select new { OrderId = order.OrderId, OrderDate = order.OrderDate, CustomerName = customer.CustomerName };

foreach (var item in query)
{
    Console.WriteLine($"{item.OrderId}, {item.OrderDate}, {item.CustomerName}");
}

输出结果为:

1, 2019-01-01 00:00:00, Alice
2, 2019-01-02 00:00:00, Bob
3, 2019-01-03 00:00:00, Alice
CrossJoin操作符

CrossJoin操作符用于将两个序列中的所有元素进行组合。它的语法为:

CrossJoin<TOuter, TInner, TResult>(IEnumerable<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TInner, TResult> resultSelector)

该方法有三个参数:

  • outer:需要查询的第一个序列。
  • inner:需要查询的第二个序列。
  • resultSelector:用于组合两个序列中元素的函数。

使用示例:

var colors = new List<string> { "Red", "Yellow", "Green" };
var fruits = new List<string> { "Apple", "Banana", "Orange" };

var query = from color in colors
            from fruit in fruits
            select new { Color = color, Fruit = fruit };

foreach (var item in query)
{
    Console.WriteLine($"{item.Color}, {item.Fruit}");
}

输出结果为:

Red, Apple
Red, Banana
Red, Orange
Yellow, Apple
Yellow, Banana
Yellow, Orange
Green, Apple
Green, Banana
Green, Orange

以上就是关于LINQ交叉加入操作符Join和CrossJoin的介绍。