Home >Backend Development >C++ >How Can I Efficiently Compare Two Unordered Lists for Equality in C#?
Compare unordered List
Determining whether two List
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!