Solved

Sort object using parameter for property name

Posted on 2013-01-24
2
328 Views
Last Modified: 2013-01-24
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
Comment
Question by:Eamon
2 Comments
 
LVL 42

Expert Comment

by:sedgwick
ID: 38813824
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
 
LVL 29

Accepted Solution

by:
Göran Andersson earned 500 total points
ID: 38814051
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This video discusses moving either the default database or any database to a new volume.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now