C#: Altering values for every item in an array

前端 未结 6 1319
醉梦人生
醉梦人生 2020-12-30 01:54

I\'m wondering if there is built-in .NET functionality to change each value in an array based on the result of a provided delegate. For example, if I had an array {1,

6条回答
  •  鱼传尺愫
    2020-12-30 02:34

    LINQ queries could easily solve this for you - make sure you're referencing System.Core.dll and have a

    using System.Linq;
    

    statement. For example, if you had your array in a variable named numberArray, the following code would give you exactly what you're looking for:

     var squares = numberArray.Select(n => n * n).ToArray();
    

    The final "ToArray" call is only needed if you actually need an array, and not an IEnumerable.

提交回复
热议问题