在Igroup <tkey,tsource> </tkey,tsource>中对内部集合进行排序

时间:2014-02-24 11:49:48

标签: c# sorting generics

我有一份员工列表,按部门名称分组在IEnumerable<IGrouping<string, employee>>(变量名depgrpname_sal_sort)。

我希望按照每个组中的工资按排序顺序显示这些集合。

我尝试了这个并得到了结果:

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);
    }
}

输出:

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

我是正确的还是有任何预定义的技术/方法来排序内部列表 提前致谢

1 个答案:

答案 0 :(得分:0)

这是有条件的,但如果你想要最高薪水,那么你需要使用OrderByDescending。例如:

foreach (Employee e in group.OrderByDescending(e => e.salary)) {
    // print...
}

修改

你问过如何让排序更直接......首先你可以改进分组:

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);
    }
}

这样,您只需对所有内容进行一次分组,而不是对预先分组的数据进行分组。如果您想按部门对所有内容进行分组,然后对其进行排序并将其保存分组并排序以供日后使用,那么我建议将其转换为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);
    }
}