NameValueCollection myCollection = new NameValueCollection(); string myValue = "test"; myCollection.AddIfNotNull("myKey", myValue); // This will add the key-value pair to the collection myValue = null; myCollection.AddIfNotNull("myKey", myValue); // This will not add the key-value pair to the collection
NameValueCollection myCollection = new NameValueCollection(); DictionaryThe NameValueCollection class is part of the System.Collections.Specialized package library in .NET.myDictionary = new Dictionary { {"key1", "value1"}, {"key2", null}, {"key3", "value3"} }; foreach (var pair in myDictionary) { myCollection.AddIfNotNull(pair.Key, pair.Value); // This will only add the key-value pairs with non-null values }