I have a list of employees, grouped by department name in an IEnumerable<IGrouping<string, employee>>
(variable name depgrpname_sal_sort
).
I want to display this groups of collections in sorted order by their salaries in each group.
I tried this and got the result:
foreach (var depgroupname in depgrpname_sal_sort) {
Console.WriteLine(depgroupname.Key);
var group = depgroupname.Where(g => g.depaname == depgroupname.Key);
foreach (employee e in group.OrderBy(e=>e.salary)) {
Console.WriteLine(e.empId + " " + e.empname + " " + e.depaname + " " + e.salary);
}
}
Output:
Development
105 John garry Development 45000
103 Mark Development 55000
HR
102 Roger HR 25000
101 John D HR 35000
Testing
104 John Testing 25000
am i correct or is there any predefined technique/method to sort the inner lists.
thanks in advance
That is sorted, but if you want the highest salary at the top then you need to use OrderByDescending . Example:
foreach (Employee e in group.OrderByDescending(e => e.salary)) {
// print...
}
Edit
You asked how you could make the sorting more direct...first off you could improve the grouping:
var employees = new List<Employee>() {
new Employee("John", "Development", 45000),
new Employee("Mark", "Development", 55000),
new Employee("Roger", "HR", 25000),
new Employee("Jeff", "HR", 35000),
new Employee("James", "Testing", 25000)
};
foreach (var g in employees.GroupBy(x => x.Dept)) {
Console.WriteLine(g.Key);
foreach (var e in g.OrderByDescending(x => x.Salary)) {
Console.WriteLine(" - {0} makes ${1}/year", e.Name, e.Salary);
}
}
That way you only group everything once, as opposed to grouping pre-grouped data. If you want to group everything by Department then sort it and save it grouped and sorted for later , then I would recommend converting it to a Dictionary<string, List<Employee>>
:
var employees = new List<Employee>() {
new Employee("John", "Development", 45000),
new Employee("Mark", "Development", 55000),
new Employee("Roger", "HR", 25000),
new Employee("Jeff", "HR", 35000),
new Employee("James", "Testing", 25000)
};
var grouped = employees.GroupBy(x => x.Dept)
.ToDictionary(
key => key.Key,
value => new List<Employee>(value.OrderByDescending(x => x.Salary))
);
foreach (var g in grouped) {
Console.WriteLine(g.Key);
foreach (var e in g.Value) {
Console.WriteLine(" - {0} makes ${1}/year", e.Name, e.Salary);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.