-3

i am using array control in which i am saving value one by one.

now i have to delet one of the element and refresh it simultaneuosly.

for example....

string[] arr= new string(25);

arr[0]="A";
arr[1]="B";
arr[2]="C"; and so on....

now after deleting second element via arr[1]=null;

i want refreshed array like mentioned below...

arr[0]="A";
arr[1]="C"; and so on....

please help...

thanks in advance,,,

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
neerajMAX
  • 269
  • 3
  • 4
  • 14

5 Answers5

8

It sounds like you should be using a List<string> rather than an array, this would give exactly the functionality you are describing.

Although arrays can be resized (thanks @Austin Brunkhorst), this is not "cheap" and you would you would need to move everything around yourself.

It should be noted, that with lots of inserts and removes Lists can get very inefficient, so you'd be better off with a LinkedList<string>. These have advantages and disadvantages. Google linked list for more info.

Immortal Blue
  • 1,691
  • 13
  • 27
3

If you want to resize arrays, you have to create a new and copy all elements from the old to the new one.

arr = arr.Where(s => s != null).ToArray();

If you would use a List<string> you could use methods like List.Remove or List.RemoveAt.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

When you have a static data amount you should use Array, BUT when you have dinamic data amount you should use List<>.

Maris
  • 4,608
  • 6
  • 39
  • 68
2

If you'll be adding/deleting entries at arbitrary positions in your collection a lot, you'd be better off using a LinkedList<string> instead

Nolonar
  • 5,962
  • 3
  • 36
  • 55
2

Instead of Array you can go with List

List<int> list = new List<int>();
list.Add(2);
list.Add(3);
list.Add(5);
list.Add(7);

you will get more options like

Contains

Exists

IndexOf

For Removing the items you will get the functions like

Remove ex: dogs.Remove("bulldog"); // Remove bulldog

RemoveAt ex: list.RemoveAt(1);

RemoveAll

andy
  • 5,979
  • 2
  • 27
  • 49