Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the NameValueCollection Equals method compare if two collection have the same key value pairs?

Tags:

c#

.net

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.

like image 433
ranjez Avatar asked Jan 15 '23 23:01

ranjez


2 Answers

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)));
like image 118
Mike Henry Avatar answered Jan 23 '23 20:01

Mike Henry


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.

like image 36
Brian S Avatar answered Jan 23 '23 19:01

Brian S