Buy Me a Coffee

使用C# Linq 達到像 JavaScript Map功能

在JavaScript中,map函數用於轉換陣列中的每個元素並返回一個新陣列。在C#中,可以使用IEnumerable集合上的Select LINQ擴展方法來實現相同的功能。

In JavaScript, the map function is used with arrays to transform each element and return a new array. In C#, the equivalent functionality can be achieved using the Select LINQ extension method on IEnumerable<T> collections.

以下是一個快速比較:
Here’s a quick comparison:

JavaScript: Using map

let numbers = [1, 2, 3, 4, 5];
let squaredNumbers = numbers.map(n => n * n);
console.log(squaredNumbers);  // [1, 4, 9, 16, 25]

C#: Using Select with LINQ

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        var squaredNumbers = numbers.Select(n => n * n).ToArray();

        foreach(var num in squaredNumbers)
        {
            Console.WriteLine(num);
        }
        // Output: 1, 4, 9, 16, 25
    }
}

在C#中,Select是LINQ(語言集成查詢)的一部分,需要System.Linq命名空間。Select方法適用於任何IEnumerable集合,不僅僅是陣列。

In C#, Select is part of LINQ (Language Integrated Query) and requires the System.Linq namespace. The Select method works on any IEnumerable<T> collection, not just arrays.