I have the following code:
List<List<int>> list = new List<List<int>>();
list.Add(new List<int> { 0, 1 });
if (list.Contains(new List<int> { 0, 1 })) // false
...
I'm trying to check whether the list contains {0,1}, but the condition is false (I don't know why, maybe because the 'new' keyword). If this is not the proper way, I'd like to know how to check that.
Thanks!
List<T>.Contains
calls the Equals()
method to compare objects.
Since the inner List<T>
doesn't override Equals
, you get reference equality.
You can fix this by creating a custom IEqualityComparer<List<T>>
that compares by value and passing it to Contains()
.
You can also just use LINQ:
if (list.Any(o => o.SequenceEqual(new[] { 0, 1 }))
You're checking to see if list
contains List #2 you've made, when you added List #1. Contains ordinarily checks to see if the object is contained by using the Equals method, but List does not override this method. This means that in this case, it does a reference comparison.
It is clear from your code that the two will not refer to the same List, even if their values are the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With