Question

I have a parent list as follows.

IList<List<int>> parentList = new List<List<int>>();
parentList.Add(new List<int> { 0, 1, 2 });
parentList.Add(new List<int> { 3, 4, 5 });
parentList.Add(new List<int> { 6, 7, 8 });
parentList.Add(new List<int> { 0, 4, 8 });
parentList.Add(new List<int> { 2, 4, 6 });
parentList.Add(new List<int> { 0, 3, 6 });
parentList.Add(new List<int> { 1, 4, 7 });
parentList.Add(new List<int> { 2, 5, 8 });

AS a part of my program I am generating a list

List<int> listToFind = new List<int>{1, 4, 7};

When I try to execute the following, it returns false although it should return true. Am I doing somthing wrong here?

parentList.Contains(listToFind);

Any advise would be greatly appreciated.

Thanks,

Jankajg

Was it helpful?

Solution

To compare the lists, use SequenceEqual (MSDN)

In your case, you can combine it with Any:

var containsListToFind = parentList.Any(x => x.SequenceEqual(listToFind));

Contains won't work because it uses the default .Equals method of the objects in the list. For List<T>, that is a reference comparison, not a value comparision. Since listToFind is a different object than the one in parentList, the references are different and Contains won't find anything.

OTHER TIPS

You can try the following:

parentList.Where(pl => listToFind.All(pl.Contains(lf)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top