我在C#中有这个代码示例,它从数组输出索引和值:
static void Sample_Select_Lambda_Indexed()
{
string[] arr = { "my", "three", "words" };
var res = arr.Select((a, i) => new
{
Index = i,
Val = a
});
foreach(var element in res)
Console.WriteLine(String.Format("{0}: {1}", element.Index, element.Val));
}
Run Code Online (Sandbox Code Playgroud)
输出是:
0: my
1: three
2: words
Run Code Online (Sandbox Code Playgroud)
我想在F#中进行类似的查询,并且像这样开始:
let arr = [|"my"; "three"; "words"|]
let res = query {
for a in arr do
// ???
}
Run Code Online (Sandbox Code Playgroud)
我该如何完成这个LINQ查询?
你可以使用Seq.mapi:
let res = arr |> Seq.mapi (fun i a -> ...)
Run Code Online (Sandbox Code Playgroud)
或直接使用Seq.iteri:
arr |> Seq.iteri (fun i v -> printfn "%i: %s" i v)
Run Code Online (Sandbox Code Playgroud)
要不就:
arr |> Seq.iteri (printfn "%i: %s")
Run Code Online (Sandbox Code Playgroud)