繁体   English   中英

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

[英]How to use a LINQ query to include index in Select with F#

我在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没有任何优势

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM