Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all values of a NameValueCollection to a string

I have the following code:

string Keys = string.Join(",",FormValues.AllKeys); 

I was trying to play around with the get:

string Values = string.Join(",", FormValues.AllKeys.GetValue()); 

But of course that doesn't work.

I need something similar to get all the values, but I don't seem to find the appropriate code to do the same.

P.S: I do not want to use a foreach loop since that beats the purpose of the first line of code.

like image 226
Rafael Herscovici Avatar asked Aug 06 '11 13:08

Rafael Herscovici


People also ask

How to get Value from NameValueCollection in c#?

A HasKeys() function is used to get a value that represents whether the NameValueCollection has keys that are not null. It is used to get all the values of a specified key or index from the NameValueCollection. In NameValueCollection, a Set() function is used to set or overwrite the existing value of the key.

What is the use of NameValueCollection in c#?

NameValueCollection is used to store a collection of associated String keys and String values that can be accessed either with the key or with the index. It is very similar to C# HashTable, HashTable also stores data in Key , value format . NameValueCollection can hold multiple string values under a single key.


2 Answers

var col = new NameValueCollection() { { "a", "b" }, { "1", "2" } }; // collection initializer  var values = col.Cast<string>().Select(e => col[e]); // b, 2  var str = String.Join(",", values );  // "b,2" 

Also you can create an extension method:

public static string Join(this NameValueCollection collection, Func<string,string> selector, string separator) {     return String.Join(separator, collection.Cast<string>().Select(e => selector(e))); } 

Usage:

var s = c.Join(e => String.Format("\"{0}\"", c[e]), ","); 

Also you can easily convert NameValueCollection to more handy Dictionary<string,string> so:

public static IDictionary<string,string> ToDictionary(this NameValueCollection col) {     return col.AllKeys.ToDictionary(x => x, x => col[x]); } 

Gives:

var d = c.ToDictionary(); 

As I found using Reflector, NameValueCollection.AllKeys internally performs a loop to gather all te keys, so it seems that c.Cast<string>() is more preferable.

like image 93
abatishchev Avatar answered Oct 07 '22 00:10

abatishchev


string values = string.Join(",", collection.AllKeys.Select(key => collection[key])); 
like image 43
Cheng Chen Avatar answered Oct 06 '22 23:10

Cheng Chen