1

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).

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
enbermudas
  • 1,603
  • 4
  • 20
  • 42

1 Answers1

1

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.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • Sorry to bother but I forgot to mention something quite important. It has to be AT LEAST the same amount of duplicated items. If this ``listB`` has 100 Cars and the ``listA`` only has 1, the requirements was fulfilled. Right now, the code only returns true if listB has the exact same amount of duplicates. Sorry for that! – enbermudas Mar 13 '19 at 16:15
  • @EnriqueBermúdez Didn´t you state the exact opposite with your `Car`-example? Confused. Anyway I hope you can update the condition as needed yourself. – MakePeaceGreatAgain Mar 13 '19 at 16:16
  • It is really hard to explain myself, sorry. Let me try again! ListA must contains the elements inside ListB (including duplicates) in order to achieve the objective but it does not have to be the exact same amount. It has to be that or more (>=) not equals (==). Sorry... again. – enbermudas Mar 13 '19 at 16:18
  • Works like a charm! Thanks a lot for your help! – enbermudas Mar 13 '19 at 16:25