c# - 反射获取对象属性以对列表进行排序

标签 c# sorting reflection

我想在 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));
}

我认为这对你有用。

关于c# - 反射获取对象属性以对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12210424/

相关文章:

c# - 在 MVVM 中适当处理 WPF Canvas (缩放)

java - 什么函数可以用来对 vector 进行排序?

algorithm - 对于给定的输入数组,有多少种排列方式是可能的,以便所有排列方式在快速排序的第一遍中都能给出相同的输出?

c# - 快速排序部分排序数组

c# - 实现接口(interface)和匹配属性的 MEF 加载类型

C# Mono - 属性名称

c# - 如何在 C# 中将 ListBox.items 转换为数组集合的字符串

c# - 安卓进度条消失

c# - 使 C# 控制台应用程序识别 .exe.config 文件中手动编辑的更改

java - 如果方法以 invoke 启动,Exceptions 不会导致崩溃