


How Can I Efficiently Compare Two Lists for Equality, Ignoring Order and Allowing Duplicates?
Compare List
This article explores how to compare two List
Initial plan
To ensure exact equality, i.e. both lists contain the same elements and their frequencies, it is recommended to sort the lists before comparing:
Enumerable.SequenceEqual(list1.OrderBy(t => t), list2.OrderBy(t => t))
Optimization plan
However, in order to improve performance, someone has proposed another solution:
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); }
The performance of this method is significantly better than the initial solution. It only requires the IEquatable
interface and not the IComparable
interface.
Handling various data types
In order to adapt to the situation of containing different data types (including nullable types) as keys, an improved solution can be used:
public static bool ScrambledEquals<T>(IEnumerable<T> list1, IEnumerable<T> list2, IEqualityComparer<T> comparer) { var cnt = new Dictionary<T, int>(comparer); ... }
The above is the detailed content of How Can I Efficiently Compare Two Lists for Equality, Ignoring Order and Allowing Duplicates?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the types of values returned by c language functions? What determines the return value?

C language function format letter case conversion steps

What are the definitions and calling rules of c language functions and what are the

Where is the return value of the c language function stored in memory?

How do I use algorithms from the STL (sort, find, transform, etc.) efficiently?

How does the C Standard Template Library (STL) work?
