I\'m having trouble implementing the delete function, any help would be appreciated. I have a list called memberlist that stores the persons name and number. I have everything w
Deleting is similar to what you have for adding. The suggestion to change to using List
is a good one, but it CAN be localized to your DeleteMember()
routine.
Try something like this (edited):
public void DeleteMember(string name)
{
if (ML == null)
{
Console.WriteLine(name + " had not been added before.");
}
else
{
int memberIndex = ML.ToList().FindIndex(p => p.Name == name);
if (memberIndex == -1)
{
Console.WriteLine(name + " had not been added before.");
return;
}
List<Person> tmp = new List<Person>(ML);
tmp.RemoveAt(memberIndex);
ML = tmp.ToArray();
}
}
If you change Person[] to List as suggested by @Wiktor Zychla, this code should work well:
public static List<Person> ML = new List<Person>();
public static void DeleteMember(string name)
{
var deleteMe = ML.Find(p => p.Name == name);
if (deleteMe == null)
{
Console.WriteLine(name + " had not been added before.");
}
else
{
ML.Remove(deleteMe);
}
}