Home > Software engineering >  My LINQ query is not ordering my dictionary
My LINQ query is not ordering my dictionary

Time:12-16

I have a Dictionary

Dictionary<string, List<Employee>> employees

that contains a list of employees. And I want to allow the user to display the list of employees in alphabetical order based on the state they are in.

Console.WriteLine($"If you would like to sort this list please enter one of the following choices..\n"  
                    $"'STATE', 'INCOME', 'ID', 'NAME', 'TAX' other wise enter any key.");
var sort = Console.ReadLine().ToUpper();

var employees = EmployeeRecord.employees;
List<Employee> sortedEmps = new List<Employee>();

if (sort.Contains("STATE")) 
   foreach (var list in employees.Values) {
       var columnQuery = list.OrderBy(x => x.stateCode).ToList();
       sortedEmps.AddRange(columnQuery);
   }
    
    
}
//Print out the newly ordered list
foreach (Employee r in sortedEmps) {   
    Console.WriteLine($"ID: {r.iD} Name: {r.name} State: {r.stateCode} Income:{r.income} Tax Due: {r.taxDue}"); 
}

However, it still prints out the list without ordering it. How can I get it to order alphabetically by the state code?

enter image description here

CodePudding user response:

Try sorting when you have all data merged.

if (sort.Contains("STATE")) {
   foreach (var list in employees.Values) {
       sortedEmps.AddRange(list);
   }
sortedEmps = sortedEmps.OrderBy(x => x.stateCode).ToList();
}

Also you can shorten a little the code with SelectMany as @Robert Harvey suggested

if (sort.Contains("STATE")) {
    sortedEmps  = employees.Values              
                 .SelectMany(x => x)
                 .ToList().OrderBy(o => o.stateCode).ToList();
}
  • Related