C#: Convert Dictionary<> to NameValueCollection

后端 未结 3 1383
执念已碎
执念已碎 2021-01-31 03:42

How can I convert a Dictionary to a NameValueCollection?

The existing functionality of our project returns an old-fashion

3条回答
  •  旧巷少年郎
    2021-01-31 04:02

    try this Extension to Dictionary I hope it's what you wanted:

    public static class DictionaryExtensions
    {
        public static NameValueCollection ToNameValueCollection(this IDictionary 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.

提交回复
热议问题