添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
GroupJoin Method Use the GroupJoin extension method from System.Linq with correct arguments.
C#
This page was last reviewed on May 6, 2023.
GroupJoin. This is a C# extension method. It groups one collection of objects by a key and joins those groups with another collection of keyed objects.
Extension
With this method, we create a collection where, at each key, a group of results is placed. GroupJoin is used with 3 lambda expressions.
GroupBy
group
Example. The GroupJoin method is challenging to use. It requires at least 4 arguments. We can specify these Func types with the lambda expression syntax.
Func
Info Argument one is the secondary collection. And argument two is a Func that returns the key from the first object type.
Note A Func that returns the key from the second object type, and one that stores the grouped object with the group itself.
Note 2 We use regular classes. It is probably more common to use anonymous types with GroupJoin.
Lambda
Finally We loop over the resulting collection with the foreach-loop construct. We print the results.
Foreach
using System; using System.Collections.Generic; using System.Linq; class Customer public int Code { get; set; } public string Name { get; set; } class Order public int KeyCode { get; set; } public string Product { get; set; } class Result public string Name { get; set; } public IEnumerable<Order> Collection { get; set; } public Result(string name, IEnumerable<Order> collection) this.Name = name; this.Collection = collection; class Program static void Main() // Example customers. var customers = new Customer[] new Customer{Code = 5, Name = "Sam" }, new Customer{Code = 6, Name = "Dave" }, new Customer{Code = 7, Name = "Julia" }, new Customer{Code = 8, Name = "Sue" } // Example orders. var orders = new Order[] new Order{KeyCode = 5, Product = "Book" }, new Order{KeyCode = 6, Product = "Game" }, new Order{KeyCode = 7, Product = "Computer" }, new Order{KeyCode = 7, Product = "Mouse" }, new Order{KeyCode = 8, Product = "Shirt" }, new Order{KeyCode = 5, Product = "Underwear" } // Correlate "customers" with "orders" // ... Use Code property as key for Customer. // ... Use KeyCode property as key for Order. // ... For each result, create object with Name and IEnumerable of orders. var query = customers. GroupJoin (orders, c => c.Code, o => o.KeyCode, (c, result) => new Result(c.Name, result)); // Enumerate results. foreach (var result in query) Console.WriteLine( "{0} bought..." , result.Name); foreach (var item in result.Collection) Console.WriteLine(item.Product); }
Sam bought... Underwear Dave bought...