Search code examples
c#listdictionary

I am getting System.Collections.Generic.List`1[ConsoleApp1.Program.Employee] instead of the list's contents? c#


class Employee
      {
         public string Name{get;set;}
         public int Age{get;set;}
         public int ID{get;set;}
      }

      static void Main(string[] args)
      {
        List<Employee> EmployeeList = new();

        EmployeeList.Add(new Employee() { Name = "Luís", Age = 19, ID = 1 });
        EmployeeList.Add(new Employee() { Name = "Sofia", Age = 25, ID = 2 });
        EmployeeList.Add(new Employee() { Name = "Gilberto", Age = 57, ID = 3 });
        EmployeeList.Add(new Employee() { Name = "Manuel", Age = 25, ID = 4 });
        EmployeeList.Add(new Employee() { Name = "Sofia", Age = 25, ID = 2 });


        var EmployeeDic = EmployeeList.GroupBy(i => i.Age).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
        
        foreach (var emp in EmployeeDic)
        {
                Console.WriteLine("" + emp.Key + emp.Value);
        }
        Console.ReadKey();}

I have done a lot of research and I can't get the value, just the key that is the age of the employees. What can I try next?


Solution

  • var EmployeeDic = EmployeeList.GroupBy(i => i.Age).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
    

    That line creates lists of employees by age. Specifically a list of employees aged 19, then another list of employees aged 25, then finally a list of employees aged 57.

    foreach (var emp in EmployeeDic)
    

    That line loops through the lists.

    Console.WriteLine("" + emp.Key + emp.Value);
    

    That line then outputs information about the list. This is not the intended behaviour of the code, so consequently the output is not helpful.


    The solution is to keep the code which loops around the lists, but then have another loop within that, which loops through each employee within that list.

    Like so: (replace your loop with this)

    foreach (var empList in EmployeeDic)
    {
        Console.WriteLine("Age {0}", empList.Key);
        foreach (var emp in empList.Value)
        {
            Console.WriteLine("\t{0} has an ID of {1}", emp.Name, emp.ID);
        }
    }
    

    The output of that is:

    enter image description here