Following is my Employee class
public class Employee
{
public string ProjectName { get; set; }
public string EmployeeName { get; set; }
}
Assume I have following data
var employees = new List<Employee>();
employees.Add(new Employee() { ProjectName = "NA", EmployeeName = "John" });
employees.Add(new Employee() { ProjectName = "NA", EmployeeName = "Adam" });
employees.Add(new Employee() { ProjectName = "Project2", EmployeeName = "Luis" });
employees.Add(new Employee() { ProjectName = "Project2", EmployeeName = "Rose" });
employees.Add(new Employee() { ProjectName = "Project1", EmployeeName = "Michael" });
employees.Add(new Employee() { ProjectName = "Project1", EmployeeName = "Duke" });
employees.Add(new Employee() { ProjectName = "Project3", EmployeeName = "Jacob" });
As seen above, few employees have been assigned to Project and few of them are not assigned ("NA"). My requirement is to order these employees in below manner
- First Show all employees who are not assigned to any project with employee name in ascending order
- Then show the employees ordered by each project and for each project show the employees in ascending order of their name
Expected result for above example (printing project name & employee name together).
NA -> Adam
NA -> John
Project1 -> Duke
Project1 -> Michael
Project2 -> Luis
Project2 -> Rose
Project3 -> Jacob
CodePudding user response:
You can:
- order by the equality between
ProjectName
and"NA"
- then, order by
ProjectName
- then, order by
EmployeeName
Example implementation:
var orderedEmployees = employees
.OrderByDescending(e => e.ProjectName == "NA") // First, show all employees who are not assigned to any project
.ThenBy(e => e.ProjectName) // Then show the employees ordered by each project
.ThenBy(e => e.EmployeeName) // ...with employee name in ascending order
.ToList();
That snippet gives the following result:
NA --> Adam
NA --> John
Project1 --> Duke
Project1 --> Michael
Project2 --> Luis
Project2 --> Rose
Project3 --> Jacob
Example fiddle here.
CodePudding user response:
var orderedEmployees = employees
.OrderByDescending(e => e.ProjectName == "NA")
.ThenBy(e => e.ProjectName)
.ThenBy(e => e.EmployeeName);
CodePudding user response:
Lambda expressions should be more than enough for this problem
List<Employee> sortedEmployees = employees.OrderByDescending(x => x.ProjectName == "NA").ThenBy(x => x.ProjectName).ToList();
Test it by yourself and play with the properties you can access with x => x.Properties
.
Just one comment: Be careful for null strings. You said you will have "NA", but if there is any null, your sorting will fail. You can add a default constructor or a function to replace null for "" if needed.
CodePudding user response:
var sorted = employees
.OrderByDescending(e => e.ProjectName == "NA")
.ThenBy(e => e.ProjectName)
.ThenBy(e => e.EmployeeName);
CodePudding user response:
employees
.OrderByDescending(e => e.ProjectName == "NA")
.ThenBy(e => e.ProjectName);