There is no shortcut here, unless the lists are sorted, in which case you can compare items one by one. And, obviously, I assume that the order does not matter, otherwise it is obvious that you can also compare them in turn.
Otherwise, I would suggest that the most efficient algorithm that you could get for large lists of elements would probably be something like this, using a hash table to track what you saw (warning: not verified, but should be clear what i get.)
public static bool IsEqual<T>(this List<T> x1, List<T> x2) { if(x1.Count != x2.Count) return false; var x1Elements = new Dictionary<T, int>(); foreach(var item in x1) { int n; x1Elements.TryGetValue(item, out n); x1Elements[item] = n+1; } foreach(var item in x2) { int n; x1Elements.TryGetValue(item, out n); if(n <= 0) return false; // this element was in x2 but not x1 else x1Elements[item] = n-1; } // make sure x1 didn't have any elements // that weren't in x2 return x1Elements.Values.All(x => x == 0); }
mquander
source share