我在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));
}
输出是:
0: my
1: three
2: words
我想在F#中进行类似的查询,并且已经开始像这样:
let arr = [|"my"; "three"; "words"|]
let res = query {
for a in arr do
// ???
}
我将如何完成此LINQ查询?
答案 0 :(得分:9)
您可以使用Seq.mapi
:
let res = arr |> Seq.mapi (fun i a -> ...)
或直接使用Seq.iteri
:
arr |> Seq.iteri (fun i v -> printfn "%i: %s" i v)
或只是:
arr |> Seq.iteri (printfn "%i: %s")
答案 1 :(得分:3)
这是一种方式:
let arr = [|"my"; "three"; "words"|]
let res = Array.mapi(fun index value -> (index, value)) arr
for (index, value) in res do
printfn "%i: %s" index value
答案 2 :(得分:1)
如果你想使用Linq:
open System.Linq
let Sample_Select_Lambda_Indexed =
let arr = [| "my"; "three"; "words" |]
let res = arr.Select(fun a i -> i,a)
res.ToList().ForEach(fun el -> let x,y = el in printfn "%i - %s" x y )
打印:
0 - my
1 - three
2 - words
链接:https://dotnetfiddle.net/uQfoI1
但在这种情况下我没有看到Linq的任何优势