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()
This entry was posted in Programming and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.