C#: Convert Dictionary<> to NameValueCollection

后端 未结 3 1369
执念已碎
执念已碎 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 03:54

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

提交回复
热议问题