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
Release: 2025-01-21 07:52:08
Original
748 people have browsed it

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:

Enumerable.SequenceEqual(list1.OrderBy(t => t), list2.OrderBy(t => t))
Copy after login

Optimization solution for IEquatable elements

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

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);
}
Copy after login

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:

public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2, IEqualityComparer<T> comparer) {
    var cnt = new Dictionary<T, int>(comparer);
    ...
}
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template