How to use LINQ query to include index in Select with F #

I have this sample code in C # that outputs an index and a value from an array:

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));
}

Output:

0: my
1: three
2: words

I want to make a similar request in F # and started like this:

let arr = [|"my"; "three"; "words"|]

let res = query {
    for a in arr do
    // ???
}

How do I end this LINQ query?

+4
source share
3 answers

You can use Seq.mapi:

let res = arr |> Seq.mapi (fun i a -> ...)

or just use Seq.iteridirectly:

arr |> Seq.iteri (fun i v -> printfn "%i: %s" i v)

or simply:

arr |> Seq.iteri (printfn "%i: %s")
+8
source

Here is one way:

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
+3
source

If you want to use 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 ) 

Print

0 - my
1 - three
2 - words

Link: https://dotnetfiddle.net/uQfoI1

But I do not see any Linq advantage in this case

+1
source

All Articles