c# – Update an element of a generic list by a specific item

Question:

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

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

        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 = "claudia_limeira@email.com";

        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; }
}

Answer:

I redid the code giving a more general solution, I believe you can take what you don't need:

using static System.Console;
using System.Collections.Generic;
using System.Linq;
                    
public class Program {
    public static void Main(string[] args) {
        var alunos = new List<Aluno> {
            new Aluno() { AlunoId = 1, Nome = "Cláudia", Email = "claudia@email.com" },
            new Aluno() { AlunoId = 2, Nome = "Pedro",   Email = "pedro@email.com" },
            new Aluno() { AlunoId = 3, Nome = "Eduardo", Email = "eduardo@email.com" }
        };
        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("==================================");
        }
    }
}

class Aluno {
    public int AlunoId { get; set; }
    public string Nome { get; set; }
    public string Email { get; set; }
}

See working on ideone . And in .NET Fiddle . Also posted on GitHub for future reference .

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

In your code the code uses Where and FisrtOrDefault . This is redundant as the second already does what the first does in a more context-appropriate way (the first tends to be slower). Then the code receives the item. The ideal is to change it and you preferred to find its index to change by index as informed in the previous question. Only in this case you don't 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 some other way (returning the index and not the item).

Also note 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 it.

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.

Scroll to Top