How to return values from a List in C #

2

I have a class Funcionario that has attributes: CPF , Nome and Salario .

I have to create an X amount of instances of this class in a List<> and after that, return to the user the values of this list. With the code I created I did not get the values of the properties of each instance, just the namespace and class.

aumento_funcionario.funcionario

I wonder why. Follow my code.

//Código da classe Program.cs
using System;
using System.Collections.Generic;
using System.Globalization;

namespace aumento_funcionarios
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Quantos funcionários serão cadastrados? ");
            int qtde_cadastros = int.Parse(Console.ReadLine());

            List<funcionario> Lista = new List<funcionario>();

            for (int i = 0; i < qtde_cadastros; i++)
            {
                Console.WriteLine("Dados do " + (i + 1) + "º funcionário: ");
                Console.Write("CPF: ");
                int cpf = int.Parse(Console.ReadLine());
                Console.Write("Nome: ");
                string nome = Console.ReadLine();
                Console.Write("Salário: ");
                double salario = double.Parse(Console.ReadLine());
                Lista.Add(new funcionario(cpf, nome, salario));
                Console.WriteLine();
            }

            for (int i = 0; i < Lista.Count; i++)
            {
                Console.WriteLine(Lista[i]);
            }

            Console.ReadLine();
        }
    }
}




//Código classe Funcionarios
    using System;
    using System.Collections.Generic;
    using System.Globalization;

    namespace aumento_funcionarios
    {
        class funcionario
        {
            public int CPF;
            public string Nome;
            public double Salario { get; private set; }

            public funcionario (int cpf, string nome, double salario)
            {
                this.CPF = cpf;
                this.Nome = nome;
                this.Salario = salario;
            }

        }
    }
    
asked by anonymous 03.09.2018 / 14:45

4 answers

4
What happens is that when you ask to write in the console the list of employees and since employees is not a simple type, but a composite object, the compiler can not print it the way you want, I made a modify in your code how the print will work, then, following the logic, you can modify what is best for you. Here is the code:

public static void Main()
{
    Console.Write("Quantos funcionários serão cadastrados? ");
        int qtde_cadastros = int.Parse(Console.ReadLine());

        List<funcionario> Lista = new List<funcionario>();

        for (int i = 0; i < qtde_cadastros; i++)
        {
            Console.WriteLine("Dados do " + (i + 1) + "º funcionário: ");
            Console.Write("CPF: ");
            int cpf = int.Parse(Console.ReadLine());
            Console.Write("Nome: ");
            string nome = Console.ReadLine();
            Console.Write("Salário: ");
            double salario = double.Parse(Console.ReadLine());
            Lista.Add(new funcionario(cpf, nome, salario));
            Console.WriteLine();
        }

        for (int i = 0; i < Lista.Count; i++)
        {
            Console.WriteLine(Lista[i]);
        }

        Console.ReadLine();
}

class funcionario
    {
        public int CPF;
        public string Nome;
        public double Salario { get; private set; }

        public funcionario (int cpf, string nome, double salario)
        {
            this.CPF = cpf;
            this.Nome = nome;
            this.Salario = salario;
        }
        public override string ToString()
        {
            return "funcionario: " + this.CPF + " " + this.Nome + " " +this.Salario + "\n";
        }
    }

}

What I did was override the writing method of the employee object so that when called it prints the attributes. I hope I have helped

    
03.09.2018 / 14:57
7

There are several problems in the code, some just in style. The biggest one is that it is trying to convert something that is not guaranteed that can be converted and this will break the application if the typing is wrong. The right thing is to check before using. I even though I finished the application for simplicity, but you can issue an error message and ask again to enter until a valid value is entered. In real code people create codes that do this in each item and put it into function for easy use.

Note that I have changed a lot of things in the code, such as how to print, the names of things, and the use of foreach instead of for . It should be the preference, until only for resolves. I used names within the C # naming pattern .

If you used a property in a class field, why not use at all? Or why not use field at all if used in two of them? Keep a pattern. Even keep the correct uppercase and lowercase pattern, which I left wrong.

You were ordering the list. It does not have an automatic printing medium of it that comes out as you imagine. There are endless ways to print a list, you have to assemble this item by item. And even within the item also has many ways to print each member of the list item, so have to deal with it. Until the list was picking up each item, but not every member.

using static System.Console;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        Write("Quantos funcionários serão cadastrados? ");
        if (!int.TryParse(ReadLine(), out var quantidade)) return;
        var lista = new List<Funcionario>();
        for (int i = 0; i < quantidade; i++) {
            WriteLine($"Dados do {(i + 1)}º funcionário: ");
            Write("CPF: ");
            if (!int.TryParse(ReadLine(), out var cpf)) return;
            Write("Nome: ");
            var nome = ReadLine();
            Write("Salário: ");
            if (!double.TryParse(ReadLine(), out var salario)) return;
            lista.Add(new Funcionario(cpf, nome, salario));
            WriteLine();
        }
        foreach (var item in lista) WriteLine($"CPF: {item.Cpf} - Nome: {item.Nome} - Salário: {item.Salario}");
    }
}

public class Funcionario {
    public int Cpf;
    public string Nome;
    public double Salario { get; private set; }
    public Funcionario (int cpf, string nome, double salario) {
        Cpf = cpf;
        Nome = nome;
        Salario = salario;
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I put it in GitHub for future reference .

    
03.09.2018 / 15:02
1

As the list is not of a simple type, such as string, int and etc ... you need to print all attributes of the list.

In this case, it would look like this:

 for (int i = 0; i < Lista.Count; i++)
 {
      Console.WriteLine(Lista[i].Cpf);
      Console.WriteLine(Lista[i].Nome);
      Console.WriteLine(Lista[i].Salario );
 }
    
03.09.2018 / 14:51
1

As already mentioned, you should display each property of your object Funcionario of the list.

You can use the ForEach method to display, it ends up being simpler.

Lista.ForEach(funcionario =>
        {
            Console.WriteLine(funcionario.Cpf);
            Console.WriteLine(funcionario.Nome);
            Console.WriteLine(funcionario.Salario);
        });
    
03.09.2018 / 14:57