Take the analogous list for SwitchID == toID
.
var alreadyUsed = tms.TMSSwitchPorts
.Where(a => a.SwitchID == toID)
.Select(a2 => a2.PortNumber)
.ToList();
Then just check that nothing appears in both two lists.
if (currentPort.Intersect(alreadyUsed).Any())
{ // do something }
Explanation:
Any()
doesn't work the way you think it does. By itself as used above, it checks for any elements in the container. As shown in @BenAaronson's answer (which is slightly better than this answer), it checks if an IEnumerable
contains any element which for which the function argument returns true.
list1.Any(HasSomeProperty)
where HasSomeProperty
is a function which takes an element of list1
and returns a bool; or more usually with a lambda:
list1.Any(x => SomePropertyHoldsFor(x))
Edit:
I said @BenAaronson's answer was better because it allows some 'short-circuiting' optimizations that I didn't think my solution had. These are mentioned in the comments to his answer. However, with some trial and error I found that Intersect does automatically make the same optimizations - specifically it caches the 'output' of one IEnumerable for comparison with each element of the other, rather than traverse it each time. So my solution is better, as Intersect
does automatically what you have to think about a little bit for Ben's method ;) @sloth's answer involves a different automatic optimization, and is much is better for the database query using Queryable
that the asker had in mind.
This answer explains how Intersect
works - it is not really 'caching', but it only accesses each IEnumerable
once.