C# LINQ methods and their JavaScript equivalents

Here’s a breakdown of common C# LINQ methods and their JavaScript equivalents, including Sum and Avg:

Filtering (Where):

  • C#: myList.Where(x => x > 10)
  • JavaScript: myList.filter(item => item > 10)

Both methods filter the collection based on a condition. The condition is specified in an arrow function in JavaScript.

Finding First Match (Find):

  • C#: myList.Find(x => x.Name == "John")
  • JavaScript: myList.find(item => item.Name === "John")

Both methods return the first element that matches the condition. If no match is found, C# returns null while JavaScript returns undefined.

Projection (Select):

  • C#: myList.Select(x => x.ToUpper())
  • JavaScript: myList.map(item => item.toUpperCase())

Both methods transform each element in the collection based on a provided function.

Checking Existence (Any):

  • C#: myList.Any(x => x.Age < 18)
  • JavaScript: myList.some(item => item.age < 18)

Both methods check if at least one element satisfies the condition. They return true if a match is found, false otherwise.

Checking All Elements (All):

  • C#: myList.All(x => x.IsAvailable)
  • JavaScript: myList.every(item => item.isAvailable)

Both methods check if all elements meet the condition. They return true if all elements match, false otherwise.

Ordering (OrderBy):

  • C#: myList.OrderBy(x => x.Name) (ascending) or myList.OrderByDescending(x => x.Name) (descending)
  • JavaScript: myList.sort((a, b) => a.name.localeCompare(b.name)) (ascending) or myList.sort((a, b) => b.name.localeCompare(a.name)) (descending)

C# offers dedicated methods for sorting. JavaScript’s sort method requires a comparison function that defines the sorting logic. Note that localeCompare should be used for proper string comparison.

Sum:

  • C#: myList.Sum(x => x.Price)
  • JavaScript: myList.reduce((acc, item) => acc + item.price, 0)

Both methods calculate the sum of a numeric property in the collection. The reduce method in JavaScript applies a function against an accumulator and each element to get a single output value (the sum). An initial value of 0 is provided for the accumulator.

Avg (Average):

  • C#: myList.Average(x => x.Rating) (assumes Rating is a number)
  • JavaScript:
    1. Calculate the sum using reduce as explained above.
    2. Calculate the average by dividing the sum by the number of elements (myList.length).

Here’s the JavaScript code for calculating the average:

JavaScript

const averageRating = myList.reduce((acc, item) => acc + item.rating, 0) / myList.length;

Remember:

  • JavaScript methods typically modify the original array (sort), while C# LINQ methods often create a new collection.
  • JavaScript doesn’t have a direct equivalent for C#’s Single method. You can filter and then check the length for a single element.
  • Explore libraries like JS-LINQ.js for a more LINQ-like experience in JavaScript.

Comments

Leave a comment