Implementation of a set "equality"

Source: Internet
Author: User
Tags foreach bool count visual studio

Recently encountered a small function in the work, that is, to send a request to a service command, you need to determine whether the request has changed, if the change, then request again. The problem is actually to determine whether two sets are equal, simply record the collection of the last requested element and then compare it to the most recent one. What needs to be explained here is that the set equality is defined here: two sets if the element values are the same and appear the same number of times, even if the order is not the same as the same, such as set a={1,2,3,4,4,5} set b={1,4,4,2,3,5} The two sets are also considered equal. The equality of the sets discussed later is based on this assumption.

This is a simple question, there are different ways to solve, and here to share with you.

Method one uses the dictionary count to implement the

This approach is simple, creating a Dictionary object that adds the elements in the first collection as a key to the dictionary, and value is the number of occurrences. The second collection is then traversed, and if the same key is included, value is minus 1, and if it is not, return false directly to indicate that two sets are different. Finally, if the value of all keys in dictionary is 0, it means that two sets are equal, otherwise unequal.

<summary>///to determine whether two sets are equal, equality represents the value of the element and the number of occurrences, the order can be different. </summary>///<typeparam name= "T" ></typeparam>///<param name= "List1" ></param>/// <param name= "List2" ></param>///<returns></returns>public static bool Scrambledequals<t > (ienumerable<t> list1, ienumerable<t> list2)
{//If the number of sets is not equal, the collection is different if (list1). Count ()!= List2. Count ()) return False;var cnt = new dictionary<t, int> (); foreach (T s in List1)
    {if (CNT). ContainsKey (s))
        {
            cnt[s]++
        } else {
            cnt. ADD (S, 1);
        }
    } foreach (T s in List2)
    {if (CNT). ContainsKey (s))
        {
            cnt[s]--
        } else//If there is an element in the second collection that is not contained in the first collection, it means that two sets are different {return false;
        }
    } Return CNT. Values.all (c => c = 0);
}

The algorithm requires the object to implement the IEquatable interface, and the interface general object is implemented by default.

The efficiency of the above algorithm is very high, the time complexity is O (N), because the search time complexity of Dictionary is O (1), so the main time is spent on the traversal set.

The above method is right. NET version is compatible, if the. NET 2.0 version is also very easy to change, just need to change the last code to traverse. Because of the project reason, my development environment is 2.0 so only then uses this method.

Method two uses the SequenceEqual extension method of IEnumerable

In. NET 3.5, there is a new way to compare the equality of collection elements, and the IEnumerable interface provides a method called SequenceEqual that determines whether two sequences are equal in order, that is, the length of two source sequences is equal and the corresponding elements are equal.

We can sort the two sets first, then call the Enumerable.sequenceequal method directly, which is probably the simplest way to implement it.

public static bool Scrambledequalsusingsequenceequal<t> (ienumerable<t> list1, ienumerable<t> list2
{return enumerable.sequenceequal (List1). by (T => T), List2. (t => t));

Note that if you want to customize the equality feature, you need to implement the Iequatable<t> interface and provide custom equal and GetHashCode implementations.

Method Three uses Collectionassert.areequivalent method

In the Unit test framework of Visual Studio, In the Microsoft.VisualStudio.TestTools.UnitTesting namespace and in NUnit there are collectionassert.areequivalent methods, which are interpreted as follows:

"two collections are equivalent if they have the same elements in the same quantity, but in any order." Elements are equal if their values are equal, not if they to the refer object.

From the definition we can see that this is exactly the set equality we have defined. So you can use this method directly. Note that this namespace is located in the Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll DLL.

This column more highlights: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/net/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.