Any idea on how to check whether that list is a subset of another?
Specifically, I have
List<double> t1 = new List<double> { 1, 3, 5 };
List<double> t2 = new List<double> { 1, 5 };
How to check that t2 is a subset of t1, using LINQ?
Any idea on how to check whether that list is a subset of another?
Specifically, I have
List<double> t1 = new List<double> { 1, 3, 5 };
List<double> t2 = new List<double> { 1, 5 };
How to check that t2 is a subset of t1, using LINQ?
Use HashSet instead of List if working with sets. Then you can simply use IsSubsetOf()
Sorry that it doesn't use LINQ. :-(
If you need to use lists, then @Jared's solution works with the caveat that you will need to remove any repeated elements that exist.
This is a significantly more efficient solution than the others posted here, especially the top solution:
If you can find a single element in t2 that isn't in t1, then you know that t2 is not a subset of t1. The advantage of this method is that it is done all in-place, without allocating additional space, unlike the solutions using .Except or .Intersect. Furthermore, this solution is able to break as soon as it finds a single element that violates the subset condition, while the others continue searching. Below is the optimal long form of the solution, which is only marginally faster in my tests than the above shorthand solution.
I did some rudimentary performance analysis of all the solutions, and the results are drastic. These two solutions are about 100x faster than the .Except() and .Intersect() solutions, and use no additional memory.