Reputation: 1615
It might sound like this answer was asked before, but it is not the same. I was looking for a way to check if a List "A" contains all the elements from a List "B" and i got the answer from this question: Does .NET have a way to check if List a contains all items in List b?. Either way, I have a problem with this solution.
My List "A" can have a series of Item
which is an object and so can the List B and I want my code to return false if List B contains 2 times the same object and my List "A" 1 or less. This piece of code (taken from the right answer):
return !RequiredItems.Except(Application._player.InventoryItems).Any();
Only checks if the elements exists at least one time on the List "A". Example:
List A: Car
List B: Car, Car
Will return true because List A contains a Car even though I want it to return false unless it has 2 Cars.
Is there a way to modify that code in order to make what I want or there is another way to achieve this?
Edit: @HimBromBeere made me realize that I forgot to say something really important. The List A needs to have at least the same amount of elements to achieve the objective. If this List A contains 1000 Cars and List B only contains B, it should return true. It can only return false if List A has less or none elements in List B (including duplicates).
Upvotes: 1
Views: 365
Reputation: 37000
I could imagine a loop-based approach like this:
bool areEqual = true;
foreach(var g in listB.GroupBy(x => x))
{
if(listA.Count(x => x == g.Key) >= g.Count())
{
areEqual = false;
break;
}
}
It groups all duplicates of listB
and checks if their amount is at least the amount of equal items from listA
.
This of course assumes reference-equality of your duplicates. Otherwise you would have to implement some equality-check.
Upvotes: 1