0

I am trying to create selling feature where if you use the sell command and write one of the items you want to sell from your inventory(array) then it will remove the item from the array and add some money to your balance. How do I remove a specific string from an array? For example, I want to say that I want to remove the string "Carp" without specifying "inventory[0]".


long balance = 100;

string[] inventory = {"Carp", "Laptop", "Mobile"}
Console.WriteLine("What do you want to sell?"

string sellingItem = Console.ReadLine();

if(sellingItem.Equals("Carp")
{
  Console.WriteLine("Selling Carp");
  balance = balance+15;
  
  //

}


I tried to search for solutions but none of them were able to full fil my criteria.

4
  • Please provide enough code so others can better understand or reproduce the problem. Commented Jan 20, 2023 at 10:38
  • 4
    If you use List<string> instead of array, you can remove item from by doing inventory.Remove("Carp"); Commented Jan 20, 2023 at 10:40
  • Does this answer your question? How to remove item from string array in C#? Commented Jan 20, 2023 at 10:43
  • you should also mention if there are duplicate items in the array or not Commented Jan 20, 2023 at 10:45

1 Answer 1

0

You can use Linq.

For example

inventory = inventory.Where(x=> x != "Carp").ToArray();

Note this will create a new array instance.

Generally I find working with List<> easier than arrays in which case you can use and maintain the same collection object:

inventory.RemoveAll(x=> x == "Carp");

https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removeall?view=net-7.0

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.