Update an element of a generic list by a specific item

7

How do I update a specific element of a generic list by locating by ID and passing an updated object in its place, updating the name and email?

class Program
{
    static void Main(string[] args)
    {
        List<Aluno> aluno = new List<Aluno>{
            new Aluno() { AlunoId = 1, Nome = "Cláudia",Email="[email protected]" },
            new Aluno() { AlunoId = 2, Nome = "Pedro",Email="[email protected]" },
            new Aluno() { AlunoId = 3, Nome = "Eduardo",Email="[email protected]" }
        };

        Console.WriteLine("==================================");

        foreach (var item in aluno)
        {
            Console.WriteLine("ID: {0}\nNome: {1}\nEmail: {2}", item.AlunoId, item.Nome,item.Email);
            Console.WriteLine("==================================");
        }

        Console.WriteLine("\nLista Atualizada\n");

        int iElemento = 1;

        var elem = aluno.Where<Aluno>(a => a.AlunoId == iElemento).FirstOrDefault();
        int index = aluno.IndexOf(elem);

        aluno[index].Nome = "Cláudia Limeira";
        aluno[index].Email = "[email protected]";

        foreach (var item in aluno)
        {
            Console.WriteLine("ID: {0}\nNome: {1}\nEmail: {2}", item.AlunoId, item.Nome, item.Email);
            Console.WriteLine("==================================");
        }

        Console.Read();
    }
}

class Aluno
{
    public int AlunoId { get; set; }
    public string Nome { get; set; }
    public string Email { get; set; }
}
    
asked by anonymous 16.09.2015 / 21:48

3 answers

6

I have refined the code giving a more general solution, I believe you can take what you do not need:

public class Program {
    public static void Main(string[] args) {
        var alunos = new List<Aluno> {
            new Aluno() { AlunoId = 1, Nome = "Cláudia", Email = "[email protected]" },
            new Aluno() { AlunoId = 2, Nome = "Pedro",   Email = "[email protected]" },
            new Aluno() { AlunoId = 3, Nome = "Eduardo", Email = "[email protected]" }
        };
        ImprimeAlunos(alunos);
        while (true) {
            var id = 0;
            Write("Qual ID de aluno deseja modificar? (-1 para encerrar)");
            if (int.TryParse(ReadLine(), out id)) {
                if (id == -1) {
                    break;
                }
                var alunoAchado = alunos.FirstOrDefault(x => x.AlunoId == id);
                if (alunoAchado != null) {
                    Write("Qual o novo nome? ");
                    alunoAchado.Nome = ReadLine();
                    Write("Qual o novo e-mail? ");
                    alunoAchado.Email = ReadLine();
                } else {
                    WriteLine("Id inválido tente outro");
                }
            } else {
                WriteLine("Id inválido tente outro");
            }
        }
        WriteLine("Nova Lista");
        ImprimeAlunos(alunos);
    }

    static void ImprimeAlunos(List<Aluno> alunos) {
        WriteLine("==================================");
        foreach (var item in alunos) {
            WriteLine($"ID: {item.AlunoId}\nNome: {item.Nome}\nEmail: {item.Email}");
            WriteLine("==================================");
        }
    }
}

See working on dotNetFiddle .

Note that in the case of doing a search using LINQ the return is the item itself, so you do not need to use index to access it. What is changed in the item found will be reflected in the student list.

In your code, the code uses Where and FisrtOrDefault . This is redundant since the second one already does what the former does in a more appropriate way to the context (the former tends to be slower). Then the code receives the item. Ideally you should change it and you would prefer to find his index to change by the index as you were informed in the previous question. Except in this case you do not need it, it's unnecessary work. Unless the problem requires you to do this, which I doubt, but then it would be better to solve it otherwise (returning the index, not the item).

Note also that I used a more modern coding style. If you have any specific questions ask for clarification or open a question if you think the topic deserves.

You can improve it even more, you can validate more things, but this is the basics.

I made another version without using LINQ . That is, I did what LINQ would do.

    
16.09.2015 / 21:55
4

To locate the item, you need to do:

var item = aluno.First(x => x.Id == 1); //Localizando o aluno com id 1

To update it:

item.Nome = "Novo nome";
item.Email = "[email protected]";

As Aluno is a type by reference , when you change the object item , the object inside will also be updated.

    
16.09.2015 / 21:53
1

You can create a crud to take care of the list :) o

Type this o

    private List<Obj> listaDeObjetos = new List<Obj>();

    public void Add(Obj obj)
    {
        listaDeObjetos.Add(obj);
    }

    public Obj Get(int id)
    {
        return listaDeObjetos.Find(c => c.Id == id);
    }

    public void Remove(Obj obj)
    {
        listaDeObjetos.Remove(obj);
    }

    public void Update(Cart objQueVaiSerAtualizado)
    {
        var objQueVaiSerRemovido= Get(objQueVaiSerAtualizado.Id);
        Remove(objQueVaiSerRemovido);
        Add(objQueVaiSerAtualizado);
    }

As to remove an object from a list it is necessary to pass the object, so the update becomes the more "complex" of the methods.

in the update method: you call it passing the object that will be updated, say you changed the name, which is a property of the object and such, then you pass the obj with the new name, list using the Get method passing the id of the object to be updated, the get method returns the object that is in the list and the name has not been changed, with this object you go to the remove method, which will remove this outdated object in sequence calls the add to add the updated object.

    
05.02.2017 / 20:37