[英]sort inner collections in Igroup<Tkey,Tsource>
I have a list of employees, grouped by department name in an IEnumerable<IGrouping<string, employee>>
(variable name depgrpname_sal_sort
). 我有一个员工列表,按
IEnumerable<IGrouping<string, employee>>
(变量名称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 . 那是有序的,但是如果您想在最高薪水最高,那么您需要使用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>>
: 如果要按部门对所有内容进行分组,然后对其进行排序, 然后将其分组并保存以供以后使用 ,那么我建议将其转换为
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.