反射获取对象属性来对列表进行排序

我想在c#中对存储在其中的对象的属性进行排序。 我有这个:

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));
    }
 }

它工作正常,但我想要更通用一些,以便不必知道该字段进行排序。 我有这样的想法:

//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));
}

显然这不起作用,但这是我想要的。 有没有可能?

谢谢。


反射代码不正确,看看这个

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));
}

我认为这会对你有用。


这是我用于同样的问题。

用法如下所示: 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/63067.html

上一篇: Reflection get object property to sort a list

下一篇: EF4 Code First + SQL Server CE: save bidirectional reference atomically