If not what is the best way to determine if two NameValueCollections objects are equal.
I am using it to determine if two query strings parsed into a namevaluecollection have the same keys and values regardless of order.
Equals does not appear to do what you want. It appears to check reference equality, not that they are equivalent.
The following method should work (using System.Linq), though there's probably a more efficient way:
public bool CompareNameValueCollections(NameValueCollection nvc1,
NameValueCollection nvc2)
{
return nvc1.AllKeys.OrderBy(key => key)
.SequenceEqual(nvc2.AllKeys.OrderBy(key => key))
&& nvc1.AllKeys.All(key => nvc1[key] == nvc2[key]);
}
Note: If order does matter, the OrderBy statements could be dropped. If there are multiple values per key and you need to check that values are equivalent regardless of order, then the last line could be changed to something like:
&& nvc1.AllKeys
.All(key => nvc1.GetValues(key)
.OrderBy(val => val)
.SequenceEqual(nvc2.GetValues(key)
.OrderBy(val => val)));
I would recommend creating a helper method or something similar that manually compares the keys/values of the collections so you can determine if they are equal for what you need.
Remember, there are lots of variables that will depend on your specific case - if the collections have the same contents (keys & values), but in different order, are they equal? Are the collections equal if the contents are the same (value equality), but do not have reference equality, or must they be the same instances for all keys and values? Etc.
So there probably isn't a one-size fits all solutions built into the framework - you'll need to write some code to compare the two collections against the criteria you need to determine equality.
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