0

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

1
  • 1
    I'm failing to understand how you would add items to an array with the example you have. Commented Dec 18, 2010 at 11:15

4 Answers 4

4

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.

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

1 Comment

perhaps HashSet if the indexed value is not important.
2

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");

Comments

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

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

Comments

0

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;
            }
        }           

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.