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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With