Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 343
  • Last Modified:

Sort object using parameter for property name

This seems to work it sorts my list of ProjectActions by DueDate

actionList.Sort(delegate(ProjectAction al1, ProjectAction al2) { return al1.DueDate.CompareTo(al2.DueDate); });

I would like to pass in the property to sort by as a parameter

string SortBy = "DueDate"

something like this.
al1(SortBy).compareto al2(SortBy)

Is it possible to do this
0
Eamon
Asked:
Eamon
1 Solution
 
Meir RivkinFull stack Software EngineerCommented:
you don't need to pass the property as string, use OrderBy:

actionList.OrderBy(n=>n.DueDate);

Open in new window


you can also sort by multiple properties, for instance:

actionList.OrderBy(n => n.DueDate).ThenBy(n =>n.Property2).ThenBy(n => n.Property3);

Open in new window

0
 
Göran AnderssonCommented:
It would be possible, but very complicated because you would need to use reflection to get the properties, and still have different code for different data types.

Create a delegate depending on the parameter name. Example:

Func<ProjectAction, ProjectAction, bool> compare;
switch (SortBy) {
  case "Name": compare = (x, y) => x.Name.CompareTo(y.Name); break;
  case "DueDate": compare = (x, y) => x.DueDate.CompareTo(y.DueDate); break;
  default: throw new NotImplementedException();
}

Open in new window

Then sort the list using the delegate:

actionList.Sort(compare);

Open in new window

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now