如何使用LINQ查询在Select中包含索引



我在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查询?

您可以使用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")

有一种方法:

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

如果你想使用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在这种情况下有什么优势

相关内容

  • 没有找到相关文章

最新更新