Skip to Content
Course content

191: Any, All, Contains

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I was working on a small RPG inventory system the other day, and I realized I was writing way too many foreach loops just to answer simple "yes or no" questions about the player's bag. You know the pattern: initialize a boolean to false, loop through the list, set it to true if you find a match, then break. It's clunky. Let's see if we can clean that up using LINQ.

The "Do I even have it?" problem

Suppose we have a list of items in a player's inventory. I want to know if they have a "Magic Crystal" so I can trigger a dialogue event. My first instinct is to just check if the list contains that exact string.

var inventory = new List<string> { "Rusty Sword", "Health Potion", "Magic Crystal", "Old Map" };

if (inventory.Contains("Magic Crystal"))
{
    Console.WriteLine("The crystal glows in your hand!");
}

This works perfectly for exact matches. Contains is straightforward; it's basically asking, "Is this specific object inside this collection?" But here's where I hit a wall: what if the item is called "Magic Crystal (Cracked)" or "Magic Crystal (Pure)"? Contains is too rigid for that. It wants an exact reference or string match, or it's a no-go.

Searching for a pattern

I need something more flexible. I don't care which crystal they have, as long as it's some kind of crystal. I tried using Contains with a partial string, but that's not how it works on a List—that only checks if the list contains a string that is exactly the partial snippet. Instead, I'll try Any().

// This won't work the way I want:
// bool hasCrystal = inventory.Contains("Crystal"); 

// But this does:
bool hasAnyCrystal = inventory.Any(item => item.Contains("Crystal"));

if (hasAnyCrystal)
{
    Console.WriteLine("You have some form of crystal!");
}

Notice the difference. Any() doesn't take a value; it takes a predicate (a little function). I'm telling C#, "Go through the list and tell me if any single element satisfies this condition." It returns true the moment it finds the first match and stops looking. It's much more powerful than Contains because I can put any logic I want inside that lambda expression.

The strict requirement

Now, let's say the player is trying to enter a "Holy Zone." To enter, every single item in their active gear slot must be "Blessed." If they're carrying even one cursed item, they're blocked. I could use Any() to check for cursed items and flip the result, but that feels like double-negative logic, which is a recipe for bugs.

I'll try All() instead.

var activeGear = new List<string> { "Blessed Shield", "Blessed Boots", "Blessed Helm" };

bool canEnter = activeGear.All(item => item.StartsWith("Blessed"));

Console.WriteLine($"Entry granted: {canEnter}"); // True

I decided to test what happens if I add a "Rusty Dagger" to that list. I expected it to fail, and it did. All() is the opposite of Any(); it only returns true if every single element meets the criteria. If the list is empty, All() actually returns true (which is a weird mathematical quirk called "vacuous truth"), but for most of our game logic, it's the perfect way to enforce strict requirements.

So, here is how I wrap my head around these three: Contains is for "Is this exact thing here?", Any is for "Is there at least one thing that fits this description?", and All is for "Does everything here fit this description?"




📋 Practical Task

The Vault Security Scanner

You are building a security system for a high-tech vault. You have a list of AccessCard objects, and you need to write a validation method to determine if a group of people can enter.

Requirements:

  • Create a class AccessCard with two properties: string OwnerName and int SecurityLevel.
  • Create a List<AccessCard> containing at least 3-5 cards.
  • Write a program that checks the following:
    1. Does the list contain a card owned by "Admin"? (Use Any).
    2. Are ALL cards in the list at Security Level 5 or higher? (Use All).
    3. Is there any card with a Security Level of 0 (Unauthorized)? (Use Any).
  • Print the result of each check to the console with a descriptive message.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.