A join of two data sources is the association of objects in one data source with objects that share a common attribute in another data source.
Join
Joins two sequences based on key selector functions and extracts pairs of values.
Method Syntax
// 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" }
Query Syntax
// 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
Joins two sequences based on key selector functions and groups the resulting matches for each element.
Method Syntax
// 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" }
Query Syntax
// 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" }
Zip
Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
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 |