var SameNames = ListA.All(x => ListB.All(y => y.Name.Equals(x.Name)));
What you wrote here is a requirement that all names in A match all names in B. That clearly conflicts with your example data, as the "Marc" from A does not equal "Jolie" from B.
Your current code would only return true if A and B in total only contain one distinct name. Which makes no sense for the problem you're trying to solve.
What you're actually trying to solve is if all names from A have one match in B. That would be achieved by doing:
var sameNames = listA.All(a => listB.Any(b => b.Name.Equals(a.Name)));
Note the Any
. It returns true
if it find (at least) one match. This is different from All
, which only returns true if all values in B are a match.
However, this is not enough yet. You've now ascertained that all names from A appear in B, but it's still possible that B contains more names that aren't in A. Take the following example:
var listA = new List<string>() { "Andy", "Bobby", "Cindy" };
var listB = new List<string>() { "Andy", "Bobby", "Cindy", "David" };
var SameNames = listA.All(a => listB.Any(b => b.Name.Equals(a.Name)));
SameNames
will be true
, but that's because you only one direction. You need to check in both directions:
var listA_in_listB = listA.All(a => listB.Any(b => b.Name.Equals(a.Name)));
var listB_in_listA = listB.All(b => listA.Any(a => a.Name.Equals(b.Name)));
var sameNames = listA_in_listB && listB_in_listA;
This gives you the result you want.
Note that there are a few other variations on how to approach this.
If you can guarantee that each list does not contain any duplicates, then instead of doing the same check twice, you can simple do one of the checks and then confirm that the lists are of equal length:
var listA_in_listB = listA.All(a => listB.Any(b => b.Name.Equals(a.Name)));
var sameLength = listA.Length == listB.Length;
var sameNames = listA_in_listB && sameLength;
This is more efficient, but it does require knowing that your names are unique within each list.