If you must modify an array
in place then when you delete an element, you need to copy all of the following elements down one position, and put the zero at the end position:
int [] marks = new int[5] { 1, 2, 3, 4, 5};
int deleteAtIndex = 1;
for (int i = deleteAtIndex; i < marks.Length - 1; ++i)
{
marks[i] = marks[i + 1];
}
marks[marks.Length - 1] = 0;
There is no way to
resize an array
in place.
If you can just create a new array with the element removed then there are several ways to do this:
(Starting with the same
marks
array and
deleteAtIndex
as above.)
int [] marksNew = new int[marks.Length-1];
for (int i = 0, j = 0; i < marks.Length; ++i, ++j)
{
if (i != deleteAtIndex)
marksNew[j] = marks[i];
else
++i;
}
marks = marksNew;
or (using Linq):
marks = marks.Where((_, ix) => ix != deleteAtIndex).ToArray();
or using generic List:
List<int> temp = new List<int>(marks);
temp.RemoveAt(deleteAtIndex);
marks = temp.ToArray();
Edit:
It wasn't clear if you want to remove the element based on knowing the position in the array or the value of the element. The above assume that you know the position (index) of the element to be removed. If you want to remove an element based on its value, then (for the in place removal):
int deleteValue = 2;
int deletedCount = 0;
for (int i = 0, j = 0; i < marks.Length; ++i, ++j)
{
int mi = marks[i];
if (mi != deleteValue)
{
marks[j] = mi;
}
else
{
++i;
++deletedCount;
}
}
for (int i = 0, j = marks.Length - 1; i < deletedCount; ++i, --j)
marks[j] = 0;
for the replacement array case:
marks = marks.Where(v => v != deleteValue).ToArray();
or using generic List:
List<int> temp = new List<int>(marks);
temp.Remove(deleteValue);
marks = temp.ToArray();
As Afzaal Ahmad Zeeshan said in the initial comments, using a generic List instead of an array (if you can) makes this much easier.