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.


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.


This is what I use for the same problem.

Usage looks like: mySequence.OrderByPropertyName("Login", SortDirection.Descending) .

public enum SortDirection
{
    Ascending,
    Descending
}

public static IOrderedEnumerable<T> OrderByPropertyName<T>
(
    this IEnumerable<T> items,
    string propertyName,
    SortDirection sortDirection = SortDirection.Ascending
)
{
    var propInfo = typeof(T).GetProperty(propertyName);
    return items.OrderByDirection(x => propInfo.GetValue(x, null), sortDirection);
}

public static IOrderedEnumerable<T> OrderByDirection<T, TKey>
(
    this IEnumerable<T> items,
    Func<T, TKey> keyExpression,
    SortDirection sortDirection = SortDirection.Ascending
)
{
    switch (sortDirection)
    {
        case SortDirection.Ascending:
            return items.OrderBy(keyExpression);
        case SortDirection.Descending:
            return items.OrderByDescending(keyExpression);
    }
    throw new ArgumentException("Unknown SortDirection: " + sortDirection);
}

我检查了dateTime并正常工作。

    List<DateTime> list = new List<DateTime>();
    list.Add(DateTime.Now);
    list.Add(DateTime.UtcNow.AddYears(2));

    list.Sort((x, y) => (Convert.ToString(x.GetType().GetProperty("DayOfYear").GetValue(x)).CompareTo(Convert.ToString(y.GetType().GetProperty("DayOfYear").GetValue(y)))));
链接地址: http://www.djcxy.com/p/63068.html

上一篇: 在iOS中使用Core Audio同时播放和录制

下一篇: 反射获取对象属性来对列表进行排序