'C# / Unity / Linq - How to check if a list of lists contains a specific another list?

I've got a list of list of ints like such:

    public List<List<int>> Paths = new List<List<int>>
    {
        new List<int>{0,1 },
        new List<int>{1,2 },
        new List<int>{1,3 },
        new List<int>{2,3 },
        new List<int>{2,4 },
        new List<int>{3,4 },
        new List<int>{4,5 },
    };

and I've got a path, that is just a list of int:

List<int> path = new List<int>{4,5};

How can I check if Paths contains path? I've tried if(Paths.Contains(path)) and it always yields false, even though I know I've got a list of {4, 5} in there.

I'm working on a project for unity and I've read some magic can be done using linq, so I tagged it in the title topic for future google users. ;)

Thanks a lot for your help!

Edit: I came up with this temporary solution, but I feel it can be done more elegant:

        public bool CheckIfPathsHaveConnection(List<int> connection)
        {
            bool hasElement = false;
            foreach(List<int> path in Paths)
            {
                if(path[0] == connection[0] && path[1] == connection[1])
                {
                    hasElement = true;
                    break;
                }
                else
                {
                    hasElement = false;
                }
            }
            return hasElement;
        }

EDIT2: Thank you all for your replies, I really appreciate the effort. Every answer was helpful and worthy of a solution, unfortunately I can only pick one as solution, so I'm picking the one that explained the most.



Solution 1:[1]

Try if (Paths.Any(x => x[0] == path[0] && x[1] == path[1]))

Solution 2:[2]

If you want a linq solution you could use a combination of Any() and All():

var containsPath = Paths.Any(p => p                 // any sub-list in 'Paths'
                           .All(q =>                // all elements of sub-list
                               path.Contains(q)));  // are contained in 'path'

Solution 3:[3]

if you want to know an index of existed path try this

    var index = IfExist(paths,path);
    
    var exist = index >= 0;
    
    public int IfExist(List<List<int>> paths, List<int> path)
    {
        for (int i = 0; i < paths.Count; i++)
            if (paths[i][0] == path[0] && (paths[i][1] == path[1])) return i;
         
         return -1;
    }

Solution 4:[4]

What you want is to test and see if any of the paths in Paths is equal to the path:

var ans = Paths.Any(p => p.SequenceEqual(path));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jimmy Jacques
Solution 2 haldo
Solution 3 Serge
Solution 4 NetMage