Home > front end >  C# / Unity / Linq - How to check if a list of lists contains a specific another list?
C# / Unity / Linq - How to check if a list of lists contains a specific another list?

Time:02-16

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;
        }

CodePudding user response:

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

CodePudding user response:

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'
  • Related