mihaifm / linq

linq.js - LINQ for JavaScript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: How to use Join Correctly?

StSchnell opened this issue · comments

This morning I tried the join method, but unfortunately I do not get the desired result.

Here my code:

var products = Enumerable.from([
  { ProductId: 1, Name: "Book nr 1", Price: 25 },
  { ProductId: 2, Name: "Book nr 2", Price: 15 },
  { ProductId: 3, Name: "Book nr 3", Price: 20 }
]);

var orders = Enumerable.from([
  { OrderId: 1, ProductId: 1 },
  { OrderId: 2, ProductId: 1 },
  { OrderId: 3, ProductId: 2 },
  { OrderId: 4, ProductId: null }
]);

/*
var joined = products            // Outer Data Source
  .join(                         // LINQ Inner Join
  orders,                        // Inner Data Source
  "outer => products.ProductId", // Outer Key Selector
  "inner => orders.ProductId",   // Inner Key selector
  "(outer, inner) => { OrderId: inner.OrderId, ProductId: outer.ProductId, Name: outer.Name }")
  .toArray();
*/

var joined = products
  .join(
  orders,
  function(outer) { return products.ProductId },
  function(inner) { return orders.ProductId },
  function(outer, inner) { return { OrderId: inner.OrderId, ProductId: outer.ProductId, Name: outer.Name } })
  .toArray();

console.log(JSON.stringify(joined));

I expected this result:

[
  {
    "OrderId": 1,
    "ProductId": 1,
    "Name": "Book nr 1"
  }, {
    "OrderId": 2,
    "ProductId": 1,
    "Name": "Book nr 1"
  }, {
    "OrderId": 3,
    "ProductId": 2,
    "Name": "Book nr 2"
  }
]

But my result is much more than this and includes a combination of all lines.

How do I use the Join method correctly to get the desired result?

Thanks for hints and tips.

I have discovered my error:

var joined = products
  .join(
  orders,
  function(outer) { return outer.ProductId },
  function(inner) { return inner.ProductId },
  function(outer, inner) { return { OrderId: inner.OrderId, ProductId: outer.ProductId, Name: outer.Name } })
  .toArray();

In the outer and inner key selector it is necessary to return the parameter and not the enumerable.