If you are not interested in duplicates, or you are concerned about duplicates, but not too concerned about optimizing performance, then the various methods in John's answer are certainly suitable.
If duplicates and performance bother you, then something like this extension method should do the trick, although it really doesn’t meet your “shortest code” criteria!
bool hasSameElements = A.HasSameElements(B); // ... public static bool HasSameElements<T>(this IList<T> a, IList<T> b) { if (a == b) return true; if ((a == null) || (b == null)) return false; if (a.Count != b.Count) return false; var dict = new Dictionary<string, int>(a.Count); foreach (string s in a) { int count; dict.TryGetValue(s, out count); dict[s] = count + 1; } foreach (string s in b) { int count; dict.TryGetValue(s, out count); if (count < 1) return false; dict[s] = count - 1; } return dict.All(kvp => kvp.Value == 0); }
(Note that this method will return true if both sequences are null . If this is not the desired behavior, then it is easy enough to add additional null checks.)
Lukeh
source share