Tag Archives: f#

Replacing the for loop with Seq.iter

Here’s the initial function in C#:

public string BuildQuery(IEnumerable<KeyValuePair<string, string>> args)
{
    var coll = HttpUtility.ParseQueryString(String.Empty, _urlEncoder);
    foreach (var arg in args)
    {
        coll.Add(arg.Key, arg.Value);
    }
    return coll.ToString();
}

First I rewrote it in F# the following pretty naïve way, and forgot about it for a while:

member this.BuildQuery(args : IEnumerable<KeyValuePair<string, string>>) : string =
    let coll = HttpUtility.ParseQueryString(String.Empty, urlEncoder)
    for arg in args do
        coll.Add(arg.Key, arg.Value)
    coll.ToString()

But today I recurred to it and rewrote in a better way:

member this.BuildQuery(args : IEnumerable<KeyValuePair<string, string>>) : string =
    let coll = HttpUtility.ParseQueryString(String.Empty, urlEncoder)
    args |> Seq.iter (fun arg -> coll.Add(arg.Key, arg.Value))
    coll.ToString()