You can use !Except + Any :
bool list1InList2 = !list1.Except(list2).Any();
This checks if both elements have the same elements, but if list1 is contained in list2 (ignoring duplicates).
If you want to know if list2 in list1 , use:
bool list2InList1 = !list2.Except(list1).Any();
So, you had to do both checks if you wanted both lists to contain the same elements.
If you also want to consider that both lists are the same size, check list1.Count==list2.Count . But this check is not useful if you use the set method (see Harald's comment ), it makes no sense to compare counters if you ignore duplicates later.
In general, HashSet<T> has some good and effective methods for checking whether two sequences have the same elements (ignoring duplicates), dcastro already showed one.
If you want an effective solution to determine if two lists contain the same elements, the same number and not ignoring duplicates , but ignoring order (otherwise use SequenceEquals ):
public static bool SequenceEqualsIgnoreOrder<T>(this IEnumerable<T> list1, IEnumerable<T> list2, IEqualityComparer<T> comparer = null) { if(list1 is ICollection<T> ilist1 && list2 is ICollection<T> ilist2 && ilist1.Count != ilist2.Count) return false; if (comparer == null) comparer = EqualityComparer<T>.Default; var itemCounts = new Dictionary<T, int>(comparer); foreach (T s in list1) { if (itemCounts.ContainsKey(s)) { itemCounts[s]++; } else { itemCounts.Add(s, 1); } } foreach (T s in list2) { if (itemCounts.ContainsKey(s)) { itemCounts[s]--; } else { return false; } } return itemCounts.Values.All(c => c == 0); }
Using:
var list1 = new List<int> { 1, 2, 3, 1 }; var list2 = new List<int> { 2, 1, 3, 2 }; bool sameItemsIgnoringOrder = list1.SequenceEqualsIgnoreOrder(list2);
If the order and number of duplicates are calculated, use:
bool sameItemsSameOrder = list1.SequenceEqual(list2);