Reputation: 1
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
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
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
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
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