Farid-ur-Rahman
Farid-ur-Rahman

Reputation: 1

Remove Element From Array by String (text) instead of Index

I want to remove the element form the array. Actually I don't know the the index of the element and want to remove through it's value. I have tried a lot but fail. This is the function which i used to add element in the Array

    string [] Arr;
    int i = 0;
    public void AddTOList(string ItemName)
    {
        Arr[i] = ItemName;
        i++;
    }

And I want to remove the element by the value. I know the below function is wrong but I want to explain what I want:

    public void RemoveFromList(string ItemName)
    {
        A["Some_String"] = null;
    }

Thanks

Upvotes: 0

Views: 6372

Answers (4)

Jason Evans
Jason Evans

Reputation: 29186

If you want to remove items by a string key then use a Dictionary

var d = new Dictionary<string, int>();

d.Add("Key1", 3);

int t = d["Key1"];

Or something like that.

Upvotes: 4

Javed Akram
Javed Akram

Reputation: 15354

You can iterate through every value in array and if found then remove it. Something like this

        string[] arr = new string[] { "apple", "ball", "cat", "dog", "elephant", "fan", "goat", "hat" };
        string itemToRemove = "fan";
        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i] == itemToRemove)
            {
                arr[i]=null;
                break;
            }
        }           

Upvotes: 0

Cheng Chen
Cheng Chen

Reputation: 43531

Array has a fixed size, which is not suitable for your requirement. Instead you can use List<string>.

List<string> myList = new List<string>();
//add an item
myList.Add("hi");
//remove an item by its value
myList.Remove("hi");

Upvotes: 2

Tolgahan Albayrak
Tolgahan Albayrak

Reputation: 1779

List<string> list = new List<string>(A);
list.Remove(ItemName);
A = list.ToArray();

and @see Array.Resize and @see Array.IndexOf

Upvotes: 1

Related Questions