DEV Community

Cover image for Equivalencia de filter(), map() y reduce() en C#
Juan Carlos Fuentes Lamas
Juan Carlos Fuentes Lamas

Posted on

18 2

Equivalencia de filter(), map() y reduce() en C#

Conforme voy profundizando en Javascript descubro lo potente que se está volviendo este lenguaje, sobre todo desde la parte de programación funcional. A veces viene bien saber como usar en otros lenguajes dichas funcionalidades.

En este post voy a explicar la equivalencia de las funciones filter(), map() y reduce() de Javascript en C#.

filter()

Dado un array de números vamos a filtrar los que sean mayores de 5

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filterArray = myArray.filter(n => n > 5);
Enter fullscreen mode Exit fullscreen mode

Where() sería el equivalente en C#, no debemos olvidar importar Linq y en este caso como vamos a usar List también hay que importar Generics

using System.Linq;
using System.Collections.Generic;
var myArray = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var filterArray = myArray.Where(n => n > 5);
Enter fullscreen mode Exit fullscreen mode

De ambas maneras el resultado sería
[ 6, 7, 8, 9 ]

map()

Ahora sobre dicho array vamos a multiplicar todas sus posiciones por dos

const mapArray = myArray.map(n => n*2);
Enter fullscreen mode Exit fullscreen mode

La misma operación la podríamos hacer en C# con Select()

var mapArray = myArray.Select(n => n * 2);
Enter fullscreen mode Exit fullscreen mode

Con ambas operaciones el resultado sería
[ 2, 4, 6, 8, 10, 12, 14, 16, 18 ]

reduce()

Esta función es muy potente ya que lo que antes teníamos que hacer con bucles y variables para hacer un sumatorio de un array, lo podemos hacer en una línea con esta función

const sum = myArray.reduce((accum, current) => accum + current, 0);
Enter fullscreen mode Exit fullscreen mode

Su equivalencia en C# sería con el método Aggregate()

var sum = myArray.Aggregate(0, 
          (accum, current) => accum + current);
Enter fullscreen mode Exit fullscreen mode

En ambos casos el resultado sería 45

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (1)

Collapse
 
alfredojry profile image
Alfredo

Excelente resumen. Directo a favoritos. Desearia agregar por lo menos en el caso del método Select, realizar la conversión a array con .ToArray()

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay