Skip to content
Yasser Moradi edited this page Sep 1, 2015 · 1 revision

Description:

This method is similar to group by. When executed it extracts a set of key / value pairs from the source sequence. Each element in the resultant collection is a generic Lookup object, which holds the key and a subsequence containing all of the items that matched the key. Unlike group by, ToLookup does not use deferred execution.

Sample:

let emplist = [
  { name: 'Bob', department: 'IT', salary: 30000 },
  { name: 'Dan', department: 'Finance', salary: 22000 },
  { name: 'Jim', department: 'IT', salary: 32000 },
  { name: 'Jon', department: 'Finance', salary: 24000 },
  { name: 'Ken', department: 'Sales', salary: 37000 },
  { name: 'Liz', department: 'Finance', salary: 24000 },
  { name: 'Mel', department: 'IT', salary: 40000 },
  { name: 'Sam', department: 'Sales', salary: 34000 },
  { name: 'Tim', department: 'Finance', salary: 45000 }
];

let byDept = emplist.asEnumerable().toLookup(e => e.department, e => e);

for (let i = 0; i < byDept.length; i++) {
  console.log(byDept[i].key);

  for (let j = 0; j < byDept[i].elements.length; j++)
    console.log('     ' + byDept[i].elements[j].name + ' - ' + byDept[i].elements[j].salary);
}
Clone this wiki locally