Introduction
I have been working with C# for 10 years, and in the last 4 years, I started to use JS in the front-end into deep.
I want to compare some methods related to arrays and collection in JS and C# (using LINQ). I want to show you how to choose the right method depending on your requirements in JS or C#.
forEach (js) vs ForEach (C# not LINQ)
This method is used to execute a function for each element in the array or collection. You can use it to update each element depending on conditions or for getting specific values.
Both methods are not a pure function, which means the original collection is affected or updated. This method is not included in LINQ (it’s on C# collections directly) but it’s important to mention it.
- //JS demo
- const array1 = [1, 2, 3, 4, 5];
- array1.forEach(element => console.log(element));
- //C# demo
- var listOfNumbers = new int[] {0,1,2,3,4,5};
- listOfNumbers.ToList().ForEach(p => Console.WriteLine(p));
filter (js) vs Where (LINQ)
This method is used to make a filter by a function depending on a condition.
Both methods are pure functions and return new collections including the record that matches the condition.
- //JS demo
- const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
- const result = words.filter(word => word.length > 6);
- //C# demo
- var listOfNumbers = new int[] {0,1,2,3,4,5};
- var evenNumbers = listOfNumbers.ToList().Where(p => p%2 == 0);
reduce (js) vs Aggregate (LINQ)
This method executes a function for each element to return only one value.
Both methods are pure functions and return a new single value with no affectations in the original collection.
- //JS demo
- const array1 = [1, 2, 3, 4, 5];
- const reducer = array1.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
- //C# demo
- var listOfNumbers = new int[] {1,2,3,4,5};
- var sumTotal = listOfNumbers.Aggregate(0,(total, currentItem)=> total+ currentItem);
sort (js) vs OrderBy (LINQ)
This method sorts the elements in the collection depending on a function or a parameter.
In JS this method is not a pure function and it updates the original collection. However, in C# this method is a pure function returning a new collection and can sort easily depending on the property selected. Also, you can use the method ‘Then’ to sort the new collection by other properties.

Guest UserPosted Jul 5, 2020, 2:26 PM
Those are great tips, and its always great to add to ones javascript skills. The only thing I just think of is that "find()" is not really supported by Internet Explorer, it comes with Edge 12 and "includes()" comes with Edge 14, so you should definitely check browser support if your client wants to support older browsers.