How to edit a list in C#?

Asked

Viewed 1,480 times

12

I want to edit a record of a client in which I can already register, consult and remove. But I have no idea how to edit just a few items without others being lost.

class Program
{
    static List<Cliente> ClienteList = new List<Cliente>();

    static void Main(string[] args)
    {
        int op = -1;

        while (op != 0)
        {
            Console.WriteLine("Digite 1 para cadastrar: ");
            Console.WriteLine("Digite 2 para consultar: ");
            Console.WriteLine("Digite 3 para remover cadastro");
            Console.WriteLine("Digite 4 para editar cadastro: ");
            Console.WriteLine("Digite 0 para sair: "); 

            op = int.Parse(Console.ReadLine());
            {
                if (op == 1)
                {
                    CadastroCliente();
                }
                else
                    if (op == 2)
                    {
                        ConsultaCadaCli();
                    }
                    else
                        if (op == 3)
                        {
                            RemoverCadastro();
                        }
                        else
                            if (op == 4)
                            {
                                EditarCliente();
                            }
            }

        }
    }
    public static void CadastroCliente()
    {
        Cliente cli = new Cliente();
        Console.WriteLine("Digite o nome: ");
        cli.Nome = Console.ReadLine();
        Console.WriteLine("Digite o CPF: ");
        cli.Cpf = int.Parse(Console.ReadLine());
        Console.WriteLine("Digite o telefone: ");
        cli.Tel = int.Parse(Console.ReadLine());
        Console.WriteLine("Digiete o endereco: ");
        cli.End = Console.ReadLine();

        ClienteList.Add(cli);

    }
    public static void ConsultaCadaCli()
    {
        int Consulta;
        Console.WriteLine("Digite seu CPF");
        Consulta = int.Parse(Console.ReadLine());
        var ConsultCadastro = ClienteList.Where(c => c.Cpf.Equals(Consulta)).FirstOrDefault();

        if (ConsultCadastro != null)
        {
            Console.WriteLine("Nome: " + ConsultCadastro.Nome);
            Console.WriteLine("CPF: " + ConsultCadastro.Cpf);
            Console.WriteLine("Telefone: " + ConsultCadastro.Tel);
            Console.WriteLine("Endereco: " + ConsultCadastro.End);
        }
        else
        {
            Console.WriteLine("Cliente nao cadastrado");
        }
    }
    public static void RemoverCadastro()
    {
        int RemCadast;
        Console.WriteLine("Digite seu CPF");
        RemCadast = int.Parse(Console.ReadLine());
        var RCli = ClienteList.Where(r => r.Cpf.Equals(RemCadast)).FirstOrDefault();

        if(RCli != null)
        {
            ClienteList.Remove(RCli);
            Console.WriteLine("Cadastro removido com sucesso. ");
        }
        else
        {
            Console.WriteLine("Cliente nao cadastrado");
        }
    }
}
  • Amanda, I’m already preparing a response and some improvements to your code.

  • @Amanda see the [tour]. You can accept one of the answers as the one that helped you the most. And you can vote on all questions and answers you find useful on the entire site, including here.

2 answers

9

It’s almost a mix of registering and consulting. You need to find the client as in the query and ask for new data as in the registration. Only instead of adding you change the data of the client found:

public static void EditarCliente()
{
    Console.WriteLine("Digite seu CPF");
    int Consulta = int.Parse(Console.ReadLine());
    var cli = ClienteList.Where(c => c.Cpf.Equals(RemCadast)).FirstOrDefault();

    if(cli != null) {
        Console.WriteLine("CPF: " + cli.Cpf);
        Console.WriteLine("Nome: " + cli.Nome);
        Console.WriteLine("Telefone: " + cli.Tel);
        Console.WriteLine("Endereco: " + cli.End);

        Console.WriteLine("Digite o nome: ");
        cli.Nome = Console.ReadLine();
        Console.WriteLine("Digite o telefone: ");
        cli.Tel = int.Parse(Console.ReadLine());
        Console.WriteLine("Digiete o endereco: ");
        cli.End = Console.ReadLine();
    } else {
        Console.WriteLine("Cliente nao cadastrado");
    }
}

You can see the complete code working on .NET Fiddle with some small improvements you can make, but still with some problems (and in the ideone). Also put on the Github for future reference.

Some possible improvements

I’m not saying that you should do this job. It’s probably beyond what you’ve learned and probably the effort is too great.

It could allow the data shown to be used for editing during data entry, which would complicate well the logic you are making. But basically this is it.

I understand that this is a naive implementation of a register. If you were to do something real, the code would have to do much more than this. Could check errors that can happen, duplicate registration, make validations, not use bad data types like int for telephone and CPF (data that will not be used in calculation should always be string), etc. It would have many changes to get something really functional, but there is no point improving just a little for something that is clearly being used as learning.

I’ve only made a few changes to maintain consistency of nomenclature throughout the code. This is very important to keep the code organized and you must learn to do from the beginning. Call of the same name things that are equal. The variables of a function are self-contained within it and do not get confused with variables of other functions. There is no risk of one disturbing the other. Therefore the variable cli query is not the same variable cli of the deletion. I took the opportunity to join the declaration with the attribution of the value of the variable where I gave. I also changed the order of the fields. The CPF being key should always be the first in the register.

When you learn more you can do something that seems more sophisticated but is actually much simpler (I’m not saying that you should change the shape in the work you have to do now):

using static System.Console;
using System.Collections.Generic;
using System.Linq;
                    
public class Cliente {
    public int Cpf {get; set; }
    public string Nome {get; set; }
    public int Tel {get; set; }
    public string End {get; set; }
}                

public class Program {
    static List<Cliente> ClienteList = new List<Cliente>();
                
    public static void Main(string[] args) {
        var op = -1;
        while (op != 0) {        
            WriteLine("Digite seu CPF (0 p/ sair)");
            if (!int.TryParse(ReadLine(), out var consulta)) continue;
            if (consulta == 0) {
                return;
            }
            var cliente = ClienteList.Where(c => c.Cpf == consulta).FirstOrDefault();
            if (cliente != null) {
                WriteLine("Nome: " + cliente.Nome);
                WriteLine("Telefone: " + cliente.Tel);
                WriteLine("Endereco: " + cliente.End);
                WriteLine("[1 - Editar] [2 - Remover] [3 - Nova consulta] [0 - Sair]");
                if (!int.TryParse(ReadLine(), out op)) continue;
                switch (op) {
                case 1:
                    CadastroCliente(cliente);
                    break;
                case 2:
                    ClienteList.Remove(cliente);
                    WriteLine("Cadastro removido com sucesso. ");
                    break;
                }
            } else {
                var novo = new Cliente() { Cpf = consulta };
                CadastroCliente(novo);
                ClienteList.Add(novo);
            }
        }
    }
    public static void CadastroCliente(Cliente cliente) {
        WriteLine("Digite o nome: ");
        cliente.Nome = ReadLine();
        WriteLine("Digite o telefone: ");
        cliente.Tel = int.Parse(ReadLine());
        WriteLine("Digite o endereco: ");
        cliente.End = ReadLine();
    }
}

Behold working in the .NET Fiddle. And in the repl it.. Also put on the Github for future reference.

6

Well, @Maniero beat me to it, but I’ll post a solution as well, because I made some changes mainly in the choice of options.

class Program
{
    static List<Cliente> ClienteList = new List<Cliente>();
    static void Main(string[] args)
    {
        int op = -1;

        while (op != 0)
        {

            Console.WriteLine("Digite 1 para cadastrar: ");
            Console.WriteLine("Digite 2 para consultar: ");
            Console.WriteLine("Digite 3 para remover cadastro");
            Console.WriteLine("Digite 4 para editar cadastro: ");
            Console.WriteLine("Digite 0 para sair: ");

            op = int.Parse(Console.ReadLine());

            //usar um switch/case é bem mais bonito que vários IFs aninhados
            switch (op)
            {
                case 1:
                    CadastroCliente();
                    break;
                case 2:
                    ConsultaCadaCli();
                    break;
                case 3:
                    RemoverCadastro();
                    break;
                case 4:
                    EditarCliente();
                    break;
            }

        }
    }

    private static void EditarCliente()
    {
        foreach(var cliente in ClienteList)
        {
            Console.WriteLine(cliente.Nome);
            Console.WriteLine("\"e\" para editar ou somente enter para ir para o próximo registro");
            var a = Console.ReadLine();
            if (a == "e")
            {                    
                Console.WriteLine("Digite o nome [{0}]: ", cliente.Nome);
                var nome = Console.ReadLine();
                Console.WriteLine("Digite o CPF [{0}]: ", cliente.Cpf);
                var cpf = Console.ReadLine();
                Console.WriteLine("Digite o telefone [{0}]: ", cliente.Tel);
                var tel = Console.ReadLine();
                Console.WriteLine("Digiete o endereco [{0}]: ", cliente.End);
                var end = Console.ReadLine();

                if (nome != "" && nome != cliente.Nome)
                    cliente.Nome = nome;

                if (cpf != "" && cpf != cliente.Cpf)
                    cliente.Cpf = cpf;

                if (tel != "" && tel != cliente.Tel)
                    cliente.Tel = tel;

                if (end != "" && end != cliente.End)
                    cliente.End = end;
            }
        }
    }
    public static void CadastroCliente()
    {
        Cliente cli = new Cliente();
        Console.WriteLine("Digite o nome: ");
        cli.Nome = Console.ReadLine();
        Console.WriteLine("Digite o CPF: ");
        cli.Cpf = Console.ReadLine();
        Console.WriteLine("Digite o telefone: ");
        //o telefone tem que ser uma string
        cli.Tel = Console.ReadLine().ToString();
        Console.WriteLine("Digiete o endereco: ");
        cli.End = Console.ReadLine();


        ClienteList.Add(cli);

    }
    public static void ConsultaCadaCli()
    {
        int Consulta;
        Console.WriteLine("Digite seu CPF");
        Consulta = int.Parse(Console.ReadLine());
        var ConsultCadastro = ClienteList.Where(c => c.Cpf.Equals(Consulta)).FirstOrDefault();

        if (ConsultCadastro != null)
        {
            Console.WriteLine("Nome: " + ConsultCadastro.Nome);
            Console.WriteLine("CPF: " + ConsultCadastro.Cpf);
            Console.WriteLine("Telefone: " + ConsultCadastro.Tel);
            Console.WriteLine("Endereco: " + ConsultCadastro.End);
        }
        else
        {
            Console.WriteLine("Cliente nao cadastrado");
        }


    }
    public static void RemoverCadastro()
    {
        int RemCadast;
        Console.WriteLine("Digite seu CPF");
        RemCadast = int.Parse(Console.ReadLine());
        var RCli = ClienteList.Where(r => r.Cpf.Equals(RemCadast)).FirstOrDefault();

        if (RCli != null)
        {
            ClienteList.Remove(RCli);
            Console.WriteLine("Cadastro removido com sucesso. ");
        }
        else
        {
            Console.WriteLine("Cliente nao cadastrado");
        }
    }
}
  • This way I can only edit the first registration.

  • if you keep giving enter, it doesn’t keep changing the records?

  • Yeah. But if it’s too many records, I’ll have to keep looking for one by one?

  • is, the most important of the example was to show how you do to change the list item, now you can try applying some filter methods.

  • @bigown edited his example, it’s much more sophisticated than mine. Just a question, what is the application of this example? It’s some college job?

  • It’s a college job.

  • Blz then comments on the note taken there...

  • @Amanda Pablo chose to do what he calls Browse, go one by one until you find what you want and choose it to edit. My code I use to do the same as what you did in the query, asks which you want to see and allows you to edit it. Then I made a complementary example that you can take advantage of or not where all operations were concentrated on the same code since it’s all very similar.

  • @Amanda the most important thing is to do what the teacher asked if we are to search as far as possible the examples can happen of running away from what needs to be done to the proposed problem. Since it’s college work, make it simple, but have everything you’ve learned so far, so you can get a good grade.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.