Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection get object property to sort a list

I want to sort a list in c#, by a property of the objects stored in it. I have this:

if (sortColumn == "Login")
{
    if (sortDir == "ASC")
    {
        filteredList.Sort((x, y) => string.Compare(x.Login, y.Login, true));
    }
    else
    {
        filteredList.Sort((x, y) => string.Compare(y.Login, x.Login, true));
    }
 }

And it works fine, but I want to do it more generic, in order to not to have to know the field to sort. I have thinking in something like this:

//With sortColumn = "Login";
if (sortDir == "ASC")
{
    filteredList.Sort((x, y) => string.Compare(x.GetType().GetProperty(sortColumn), y.GetType().GetProperty(sortColumn), true));
}
else
{
    filteredList.Sort((x, y) => string.Compare(y.GetType().GetProperty(sortColumn), x.GetType().GetProperty(sortColumn), true));
}

Obviously this doesn't work, but this is what I want. Is it possible by any way?

Thanks.

like image 438
christiansr85 Avatar asked Aug 31 '12 07:08

christiansr85


People also ask

How do you sort a list of objects by some properties?

In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.

How do I sort a list in C#?

Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.


1 Answers

the reflection code is not correct, look at this

PropertyInfo pi1 = typeof(x).GetProperty(sortColumn);
PropertyInfo pi2 = typeof(y).GetProperty(sortColumn);

//With sortColumn = "Login";
if (sortDir == "ASC")
{
    filteredList.Sort((x, y) => string.Compare(pi1.GetValue(x, null), pi2.GetValue(y, null), true));
}
else
{
    filteredList.Sort((x, y) => string.Compare(pi2.GetValue(y, null), pi1.GetValue(x, null), true));
}

i think this will work for you.

like image 111
Bahram Avatar answered Oct 16 '22 07:10

Bahram