C# and F# — numbering a list — a non-variable approach
2 min readAug 18, 2023
From time to time, you want to create an index for your list in order to make some calculations or simply to print elements with numeric order information.
A standard way in almost every language is to use a separate variable which, in this case, is supposed to be our counter. Like here, for C#:
List<string> listToIterate = new List<string>() { "one", "two", "three", "four", "five" };
int i = 1;
foreach (string item in listToIterate)
{
System.Console.WriteLine($"A list index: {i}, a list element: {item}");
i += 1;
}
And F# here:
let listToIterate = [ "one"; "two"; "three"; "four"; "five" ]
let mutable i = 0
for item in listToIterate do
printfn $"A list index: {i}, a list element: {item}"
i <- i + 1
Both C# and F# code output is:
There is an easy way in both instances to make code shorter and more concise.
For C# we can use LINQ:
List<string> listToIterate = new List<string>() { "one", "two", "three", "four", "five" };
foreach (var item in listToIterate.Select((listEmlement, i) => (listEmlement, i)))
{
Console.WriteLine($"A list index: {item.i}, a list element: {item.listEmlement}");
}
For F#, we use a pipeline that indexes a list at the first step, then iterates through a new list and prints every element.
let listToIterate = [ "one"; "two"; "three"; "four"; "five" ]
listToIterate
|> List.indexed
|> List.iter (fun (i, item) -> printfn "A list index: %d, a list element: %s" i item)