How can I convert a Dictionary<string, string>
to a NameValueCollection
?
The existing functionality of our project returns an old-fashioned NameValueCollection
which I modify with LINQ. The result should be passed on as a NameValueCollection
.
I want to solve this in a generic way. Any hints?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
Why not use a simple foreach
loop?
foreach(var kvp in dict)
{
nameValueCollection.Add(kvp.Key.ToString(), kvp.Value.ToString());
}
This could be embedded into an extension method:
public static NameValueCollection ToNameValueCollection<TKey, TValue>(
this IDictionary<TKey, TValue> dict)
{
var nameValueCollection = new NameValueCollection();
foreach(var kvp in dict)
{
string value = null;
if(kvp.Value != null)
value = kvp.Value.ToString();
nameValueCollection.Add(kvp.Key.ToString(), value);
}
return nameValueCollection;
}
You could then call it like this:
var nameValueCollection = dict.ToNameValueCollection();
And if you like LINQ:
return dictionary.Aggregate(new NameValueCollection(),
(seed, current) => {
seed.Add(current.Key, current.Value);
return seed;
});
(source)
return source.Cast<string>()
.ToDictionary(s => s, s => source[s]);
try this Extension to Dictionary I hope it's what you wanted:
public static class DictionaryExtensions
{
public static NameValueCollection ToNameValueCollection<tValue>(this IDictionary<string, tValue> dictionary)
{
var collection = new NameValueCollection();
foreach(var pair in dictionary)
collection.Add(pair.Key, pair.Value.ToString());
return collection;
}
}
use like
var nvc = myDict.ToNameValueCollection();
note: I have constrained the key to be string because I didn't want to overgeneralize - of course you can change this with a generic type and .ToString() for the key too.
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