2 ms·
I'll show an example in C#, which has some of the best list comprehension syntax in my opinion (LINQ): from category in categories where category.Name.Cont
by tsimionescu 7y ago
I'll show an example in C#, which has some of the best list comprehension syntax in my opinion (LINQ):
from category in categories
where category.Name.Contains("food")
join product in products on product.CategoryID equals category.ID
select new {
Name = category.Name,
MostExpensive =
(from categoryProduct in productGroup
orderby categoryProduct.Price descending
select categoryProduct)
.First()
}
In C#, with HOFs, this becomes:
categories
.Where(
category => category.Name.Contains("food"))
.GroupJoin(products,
category => category.ID,
product => product.CategoryID,
(category, productGroup) => new {
Name = category.Name,
MostExpensive =
productGroup.OrderByDescending(
product => product.Price)
.First()
}
)
The second higher-oder function form has 2 disadvantages that I see: (1) for every subclause, it must mention the lambda parameter again (with more filtering/ordering/mapping this becomes much more noticeable); (2) it is easier to mess up the order of parameters, especially for something like Join/GroupJoin, which takes 5 parameters.
- 11235813213455 7y agoIt's probably this in JS: categories .filter( category => category.Name.includes('food')) .flatMap(category => { const productGroup = products.filter(product => product.CategoryID === category.ID); return productGroup.length === 0 ? [] : [{ Name: category.Name, MostExpensive: products.reduce((a, b) => a.Price < b.Price ? b : a) }]; })