Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<List<>>.Contains() not working

Tags:

c#

list

contains

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!

like image 974
balinta Avatar asked Mar 15 '12 18:03

balinta


2 Answers

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 }))
like image 172
SLaks Avatar answered Oct 17 '22 20:10

SLaks


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.

like image 31
Almo Avatar answered Oct 17 '22 20:10

Almo