Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list by column name string

Tags:

c#

list

sorting

Let's say I have a class like this

public class model
{
    public int id{get;set;}
    public string name{get;set;}
    public string department{get;set;}
}

and I have a List of type model

List<model> modelList = List<model>();

How Can I sort the modelList by its column name with sort direction?

Ways that I tried:

public List<model> sortModelList(string columnName, SortDirection direction)
{
   //Method 1:
   //The below code was unable to sort by column and unable to set the sort direction
   return modelList.Sort();

   //Method 2:
   //The below code was unable to sort by the columnName parameter and unable to set the sort direction
   return modelList.OrderBy(a=>a.name)

  //What I can do in order to sort the list by "columnName" parameter and set the sort direction? (Ascending / Descending)
}
like image 527
User2012384 Avatar asked Mar 12 '14 03:03

User2012384


3 Answers

If you need to pass column name as a parameter, then you would need to use reflection to do your comparison. You can do something like below:

modelList.OrderBy(a => a.GetType().GetProperty(columnName).GetValue(a, null));

Of course you would have to do proper null checks etc, which I am assuming you would be able to take care of.

like image 129
Charles Prakash Dasari Avatar answered Oct 17 '22 01:10

Charles Prakash Dasari


I think you're looking for the overload of Sort() that takes a comparison function .

For example:

modelList.Sort((m1, m2) => string.Compare(m1.name, m2.name));
// descending
modelList.Sort((m1, m2) => -string.Compare(m1.name, m2.name));

OrderBy has similar flexibility, but returns a new sequence which is sorted rather than modifying the original list. So, you could do:

var newList = modelList.OrderBy(m => m.name).ToList();
// descending
var newList = modelList.OrderByDescending(m => m.name).ToList();

To specify the property to be sorted by dynamically, consider the following code:

public void SortList<T>(List<T> list, string columnName, SortDirection direction)
{
    var property = typeof(T).GetProperty(columnName);
    var multiplier = direction == SortDirection.Descending ? -1 : 1;
    list.Sort((t1, t2) => {
        var col1 = property.GetValue(t1);
        var col2 = property.GetValue(t2);
        return multiplier * Comparer<object>.Default.Compare(col1, col2);
    });
}
like image 42
ChaseMedallion Avatar answered Oct 16 '22 23:10

ChaseMedallion


The correct way to do this is to write a customer comparison function.

Everything you need to know is found here: http://msdn.microsoft.com/en-us/library/w56d4y5z%28v=vs.110%29.aspx

Have a go, and come back if it still won't work.

like image 30
david.pfx Avatar answered Oct 16 '22 23:10

david.pfx