Initialize and assign values to list of ints without a loop
is there a shorter way to do t开发者_StackOverflowhis:
List<int> mins = new List<int>();
for(int i = 0; i<60; i++)
{
mins.Add(i+1);
}
Functional version also appreciated if available in c#, also f# version appreciated.
F#:
open System.Collections.Generic
let r = new List<_>( [1..60] )
C#:
var r = new List<int>(Enumerable.Range(1, 60));
In F#, I would probably write:
[ 1 .. 60 ] |> ResizeArray.ofSeq
This is the same as calling the constructor explicitly, but it has a little nicer syntax (you can use pipelining and you don't need to specify type parameter of the constructor).
This would do it for the C# version:
List<int> mins = Enumerable.Range(1, 60).ToList();
That will loop internally, admittedly. If you are happy with an IEnumerable<int>
instead, just knock off the ToList
call and you'll get lazy evaluation. You've already got F# versions now, I see :)
List<_>
in C# is a dynamic array, not linked list. In F#, List<_>
is ResizeArray<_>
.
Here's the directly translated F# version:
let mins = new ResizeArray<int> ()
for i=0 to 60-1 do
mins.Add(i+1)
You can use ResizeArray
module:
#r "FSharp.PowerPack.dll"
let mins = ResizeArray.init 60 (fun i -> i+1)
Notice that the ResizeArray<_> type is defined in F# Core, the same name module is in F# PowerPack.
精彩评论