Home >Backend Development >C++ >How Can I Efficiently Compare Two List Objects for Content Equality in C#?
Compare the contents of List
When comparing two List
If element order doesn't matter, sorting both lists before comparing is a straightforward approach. This can be achieved using the following code:
<code class="language-csharp">Enumerable.SequenceEqual(list1.OrderBy(t => t), list2.OrderBy(t => t))</code>
Alternatively, to improve performance and be compatible with types that 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) { if (cnt.ContainsKey(s)) { cnt[s]++; } else { cnt.Add(s, 1); } } foreach (T s in list2) { if (cnt.ContainsKey(s)) { cnt[s]--; } else { return false; } } return cnt.Values.All(c => c == 0); }</code>
If the data type used as the key does not support equality comparisons by default, you can use another version of the above function that takes an equality comparator as a parameter:
<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 List Objects for Content Equality in C#?. For more information, please follow other related articles on the PHP Chinese website!