Home >Backend Development >C++ >How Can I Compare Two Lists for Equality, Ignoring Element Order?
Ignore element order for list equivalence comparisons
When comparing two List<T>
objects, you usually want to check whether their elements are equal, regardless of their position in the list. Here are a few ways to accomplish this.
1. Element equality and number of occurrences
If you need two lists to contain the same elements with the same number of occurrences, it is recommended to sort before comparing:
<code class="language-csharp">Enumerable.SequenceEqual(list1.OrderBy(t => t), list2.OrderBy(t => t))</code>
2. Optimization method
To improve performance, especially when dealing with large lists, you can use this custom method, which only needs to implement IEquatable
:
<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.ContainsKey(s) ? cnt[s] + 1 : 1; } foreach (T s in list2) { if (cnt.ContainsKey(s)) { cnt[s]--; } else { return false; } } return cnt.Values.All(c => c == 0); }</code>
3. Handling nullable types
If your element is of a nullable type, you can use a dictionary's custom comparator:
<code class="language-csharp">var comparer = EqualityComparer<T>.Default; var cnt = new Dictionary<T, int>(comparer);</code>
The above is the detailed content of How Can I Compare Two Lists for Equality, Ignoring Element Order?. For more information, please follow other related articles on the PHP Chinese website!