C#: Convert Dictionary<> to NameValueCollection

纵饮孤独 提交于 2019-12-03 03:05:45

问题


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?


回答1:


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();



回答2:


And if you like LINQ:

Dictionary to NameValueCollection

return dictionary.Aggregate(new NameValueCollection(),
    (seed, current) => { 
        seed.Add(current.Key, current.Value);
        return seed;
    });

NameValueCollection to Dictionary

(source)

return source.Cast<string>()  
    .ToDictionary(s => s, s => source[s]);



回答3:


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.



来源:https://stackoverflow.com/questions/7230383/c-convert-dictionary-to-namevaluecollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!