First, you only care about the ItemIds in ListB, so:
var bIDs = ListB.Select(x => x.ItemId);
To answer the first part of your question, I would approach this by finding the intersection of the two lists (the set of all items they share). If it has at least one element in it, then there is overlap between the two.
var sharedIds = ListA.Intersect(bIDs);
if (sharedIds.Any())
// list A contains at least one ItemID which ListB contains
As for the second part, you want to see if list A is a subset of list B. Searching for this, Stack Overflow presents a clean solution:
if (!ListA.Except(bIDs).Any())
// yes, list A is a subset of list B
This snippet works because ListA.Except(bIDs)
finds the elements that ListA
has that bIDs
doesn't. If this is empty, then ListA
doesn't contain anything that bIDs
doesn't. Thus, everything that is in ListA
is also in bIDs
.
Here's an example: A = {1, 2}
; B = {1, 2, 3}
. A is a subset of B. A.Except(B)
gives you an empty set - B has both 1 and 2, so can't be in the resulting list, and there isn't anything left in B. So when A is a subset of B, A.Except(B).Any()
gives false, as there are no elements in the result; so we obviously negate it if we want to handle that case.
For completeness, if we swap A and B round such that A is not a subset of B: A = {1, 2, 3}
; B = {1, 2}
, then A.Except(B)
gives {3}
. It can't contain 1 or 2, because B contains 1 and 2. But B doesn't contain 3, so A.Except(B)
can contain it. As {3}
contains one element, it isn't empty, so A.Except(B).Any()
is true. Negated, it is false if A is not a subset of B.
My explanation is a little terse; if you want to look things up further (and I recommend you do - a little set theory can go a long way), A.Except(B)
is LINQ's name for the set difference, or relative set complement. Wikibooks has a decent introduction to set theory if you are so inclined.