Delete Function for a Menu Driven Program

后端 未结 2 1363
终归单人心
终归单人心 2021-01-29 07:09

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

相关标签:
2条回答
  • 2021-01-29 07:50

    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();
        }
    }
    
    0 讨论(0)
  • 2021-01-29 07:56

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题