Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

8
  • 2
    That is exactly what !t2.Except(t1).Any() is doing. Linq is working back to forth. Any() is asking an IEnumerable if there is at least one element. In this scenario t2.Except(t1) is only emitting the first element of t2 which is not in t1. If the first element of t2 is not in t1 it finishes fastest, if all elements of t2 are in t1 it runs the longest. Commented Nov 2, 2014 at 8:31
  • 1
    While playing around with some sort of benchmark, I found out, when you take t1={1,2,3,...9999} and t2={9999,9998,99997...9000}, you get the following measurements: !t2.Except(t1).Any(): 1ms -> t2.All(e => t1.Contains(e)): 702ms. And it get's worse the bigger the range. Commented Nov 2, 2014 at 12:21
  • 3
    This is not the way Linq works. t2.Except (t1) is returning an IEnumerable not a Collection. It only emits all of the possible items if you iterate completely over it, for example by ToArray () or ToList () or use foreach without breaking inside. Search for linq deferred execution to read more about that concept. Commented Nov 3, 2014 at 6:27
  • 1
    I'm fully aware of how deferred execution works in Linq. You can defer the execution all you want, but when you want to determine if t2 is a subset of t1, you'll need to iterate the entire list to figure it out. There is no getting around that fact. Commented Nov 3, 2014 at 7:34
  • 3
    Lets take the example from your comment t2={1,2,3,4,5,6,7,8} t1={2,4,6,8} t2.Except(t1) => first element of t2 = 1 => difference of 1 to t1 is 1 (checked against {2,4,6,8}) => Except() emits first element 1 => Any() gets an element => Any() results in true => no further check of elements in t2. Commented Nov 3, 2014 at 7:53