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.
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.
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.
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.
string values = string.Join(",", collection.AllKeys.Select(key => collection[key]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With