Home >Backend Development >C++ >How Can I Efficiently Compare Two Unordered Lists for Equality in C#?

How Can I Efficiently Compare Two Unordered Lists for Equality in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-21 07:52:08691browse

How Can I Efficiently Compare Two Unordered Lists for Equality in C#?

Compare unordered List objects for equality

Determining whether two List objects are equal is a common problem. Although they may contain the same elements, their order may be different. This begs the question: how to compare elements regardless of their order.

If the number of occurrences of each element is important, a simple solution is to sort both lists before comparing:

<code class="language-csharp">Enumerable.SequenceEqual(list1.OrderBy(t => t), list2.OrderBy(t => t))</code>

Optimization solution for IEquatable elements

For elements that only need to implement the IEquatable interface (instead of IComparable), there is a more efficient approach:

<code class="language-csharp">public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2) {
    var cnt = new Dictionary<T, int>();
    foreach (T s in list1) {
        cnt[s] = cnt.GetValueOrDefault(s, 0) + 1;
    }
    foreach (T s in list2) {
        if (cnt.ContainsKey(s)) cnt[s] -= 1;
        else return false;
    }
    return cnt.Values.All(x => x == 0);
}</code>

This scheme counts the number of occurrences of each element in the first list and then subtracts the number of occurrences from the second list. The two lists are considered equal if each count reaches zero.

Handling custom key types

If the element types are not comparable (e.g., nullable types), you can specify a comparator for the dictionary:

<code class="language-csharp">public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2, IEqualityComparer<T> comparer) {
    var cnt = new Dictionary<T, int>(comparer);
    ...
}</code>

The above is the detailed content of How Can I Efficiently Compare Two Unordered Lists for Equality in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn