F # basics: turning NameValueCollection into a nice string

Learning F # while trying to do something useful at the same time, so this is a pretty simple question:

I have req , which is an HttpListenerRequest , which has a QueryString property, with type System.Collections.Specialized.NameValueCollection . So, for the sake of clarity, let me say that I have

let queryString = req.QueryString

Now I want to create a beautiful string (not printf for the console) from its contents, but queryString.ToString() does not seem to override, so it just gives the string "System.Collections.Specialized.NameValueCollection".

So, what is single-line F # to get a good line from it, for example, "key1 = value1 \ nkey2 = value2 \ n ..."?

+4
source share
4 answers
 nvc.AllKeys |> Seq.map (fun key -> sprintf "%s=%s" key nvc.[key]) |> String.concat "\n" 
+4
source

Something like this should work:

 let nvcToString (nvc:System.Collections.Specialized.NameValueCollection) = System.String.Join("\n", seq { for key in nvc -> sprintf "%s=%s" key nvc.[key] }) 
+4
source

I use this code that handles the case of keys that have multiple values, which is legal in NameValueCollection , and I do not see in the other answers. I also use MS AntiXSS library for URL encoding of values.

Edit: Sorry, I haven't read the OP enough. I assumed that you want to turn Request.QueryString into the actual query string. I am going to leave this answer because it is still true that NameValueCollection allows more than one value for each key.

 type NameValueCollection with /// Converts the collection to a URL-formatted query string. member this.ToUrlString() = // a key can have multiple values, so flatten this out, repeating the key if necessary let getValues (key:string) = let kEnc = Encoder.UrlEncode(key) + "=" this.GetValues(key) |> Seq.map (fun v -> kEnc + Encoder.UrlEncode(v)) let pairs = this.AllKeys |> Seq.collect getValues String.Join("&", pairs) 
+1
source

kvs.AllKeys |> Seq.map (fun i -> i+ " = " + kvs.[i]) |> Seq.fold (fun st -> s + "\n" + t) ""

Ineffective and creates lots of line instances right from my head. :)

0
source

Source: https://habr.com/ru/post/1442786/


All Articles