Ad
  • Custom User Avatar

    This is perfect ;(

  • Custom User Avatar

    return a.Any(b.Contains);

    if array is null it doesn't work

  • Custom User Avatar

    Yes, definitely simpler. Not sure about more performant...maybe.

  • Custom User Avatar

    Perhaps then a.Intersect(b).Any() - even simpler and more performant

  • Custom User Avatar

    The for could also have been a foreach, btw

  • Custom User Avatar

    @amandakleeen Intersect enumerates the source; in a.Intersect(b) all of b is added to a set in a loop, then all of a is removed from that set in another loop. If the removal succeeds the item from a is returned. The removal loop is a yielding operation, meaning that as soon as an intersecting element is encountered (set.Remove returns true) it is returned etc. so it would be slightly more efficient to ask for Any() rather than Count(). This is because Any will quit enumerating the intersection as soon as it discovers there to be one item. Count will count all of them (fully enumerate), which is unnecessary if all we seek is to know if there is at least 1. Side note (which you've done) - there are differences in memory too; because b is turned into a hashset against which a is compared, on a system with more CPU than memory resource it may be better to make b the smaller of the two arrays

  • Custom User Avatar

    @phil-port under the hood, this approach could require a lot of comparisons, upto a.Length * b.Length.