基于集合属性的OrderBy字典值集合

时间:2016-04-04 11:12:43

标签: c# linq sorting dictionary

我有一个List<Department>,因为它有部门名称员工名称列表 OrderBy Dicrection 列表。现在我需要构建一个Dictionary<string, ObservableCollection<Employee>> KEY 是一个部门名称,是一个ObservableCollection,使用List<Department>

  

期望:我需要根据{{1} <{1}}中EmpNameObservableCollection<Employee> 排序使用Dictionary<string, ObservableCollection<Employee>> EmpList中的属性   LINQ

我在下面的Main()函数中为此编写了LINQ。

sortEmpName

模型类是

List<Department> DepList

void Main() { List<Department> DepList = new List<Department>() { new Department() { DepName = "HR", sortEmpName = FilterListSortDirection.SortDirection.Ascending, EmpName = new List<string>() {"Raj", "Baba"} }, new Department() { DepName = "iLab", sortEmpName = FilterListSortDirection.SortDirection.Descending, EmpName = new List<string>() {"Emma", "Kaliya"} }, new Department() { DepName = "Testing", sortEmpName = FilterListSortDirection.SortDirection.None, EmpName = new List<string>() {"Supriya", "Billa"} } }; Dictionary<string, ObservableCollection<Employee>> EmpList = DepList.Select(m => new { Dep = m.DepName, EmpCollection = new ObservableCollection<Employee>( m.EmpName.Select(k => new Employee() { EmpName = k, IsChecked = true }).ToList()) } ).ToDictionary(x => x.Dep, x => x.EmpCollection); }

的输出屏幕截图

enter image description here

public class Employee { public string EmpName { get; set; } public bool IsChecked { get; set; } } public class Department { public string DepName { get; set; } public FilterListSortDirection.SortDirection sortEmpName { get; set; } public List<string> EmpName { get; set; } } public class FilterListSortDirection { public enum SortDirection { None, Ascending, Descending } }

的输出屏幕截图

enter image description here

  

期望:我需要根据{{1} <{1}}中List<Department> DepListDictionary<string, ObservableCollection<Employee>> EmpList 排序使用EmpName中的属性   LINQ

这是我项目中复杂LINQ查询的一小部分,因此,我需要在LINQ中实现这一点。请帮助我。

  • HR =&gt;员工姓名列表应为升序
  • iLab =&gt;员工姓名列表应为降序
  • 测试 =&gt;员工姓名列表应按原始顺序排列 - (即,无变更 - 不排序)

2 个答案:

答案 0 :(得分:1)

我猜你需要这样的东西:

var EmpList = DepList.ToDictionary(p => p.DepName, p =>
    {
        var empList = p.EmpName.Select(k => new Employee() { EmpName = k, IsChecked = true });
        if (p.sortEmpName == FilterListSortDirection.SortDirection.Ascending)
        {
            empList = empList.OrderBy(q => q.EmpName);
        }
        else if (p.sortEmpName == FilterListSortDirection.SortDirection.Descending)
        {
            empList = empList.OrderByDescending(q => q.EmpName);
        }
        return new ObservableCollection<Employee>(empList.ToList());
    });

答案 1 :(得分:0)

使用OrderBy

Controller = new StepController();