C# 使用反射对列表进行排序
我有一个表,我想为每一列做排序功能 排序有两个方向asc和desc 1如何使用反射对列进行排序C# 使用反射对列表进行排序,c#,C#,我有一个表,我想为每一列做排序功能 排序有两个方向asc和desc 1如何使用反射对列进行排序 List<Person> GetSortedList(List<Person> persons, string direction, string column) { return persons.OrderBy(x => GetProperyByName(x, column)); //GetPropertyByName - ?? } 2我还想做一些我可以称之为
List<Person> GetSortedList(List<Person> persons, string direction, string column)
{
return persons.OrderBy(x => GetProperyByName(x, column)); //GetPropertyByName - ??
}
2我还想做一些我可以称之为linq操作符链的事情:
List<Person> GetSortedList(List<Person> persons, string direction, string column)
{
var linqChain;
if(direction=="up")
{
linqChain+=persons.OrderBy(x => GetProperyByName(x, column))
}
else
{
linqChain+=persons.OrderByDescending(x => GetProperyByName(x, column))
}
linqChain+=.Where(....);
return linqChain.Execute();
}
执行此操作的简单方法是使用。执行此操作的简单方法是使用。1如果要使用列的字符串名称进行排序,请使用库 2可以使用表达式对象将LINQ表达式连接在一起
Expression linqChain = persons;
if (direction == "up")
{
linqChain = linqChain.OrderBy(column);
}
else
{
linqChain = linqChain.OrderByDescending(column);
}
linqChain = linqChain.Where(...);
return linqChain.Execute();
1如果要使用列的字符串名称进行排序,请使用库 2可以使用表达式对象将LINQ表达式连接在一起
Expression linqChain = persons;
if (direction == "up")
{
linqChain = linqChain.OrderBy(column);
}
else
{
linqChain = linqChain.OrderByDescending(column);
}
linqChain = linqChain.Where(...);
return linqChain.Execute();
试试这样的
public void SortListByPropertyName<T>(List<T> list, bool isAscending, string propertyName) where T : IComparable
{
var propInfo = typeof (T).GetProperty(propertyName);
Comparison<T> asc = (t1, t2) => ((IComparable) propInfo.GetValue(t1, null)).CompareTo(propInfo.GetValue(t2, null));
Comparison<T> desc = (t1, t2) => ((IComparable) propInfo.GetValue(t2, null)).CompareTo(propInfo.GetValue(t1, null));
list.Sort(isAscending ? asc : desc);
}
试试这样的
public void SortListByPropertyName<T>(List<T> list, bool isAscending, string propertyName) where T : IComparable
{
var propInfo = typeof (T).GetProperty(propertyName);
Comparison<T> asc = (t1, t2) => ((IComparable) propInfo.GetValue(t1, null)).CompareTo(propInfo.GetValue(t2, null));
Comparison<T> desc = (t1, t2) => ((IComparable) propInfo.GetValue(t2, null)).CompareTo(propInfo.GetValue(t1, null));
list.Sort(isAscending ? asc : desc);
}
为什么要使用标签?也不需要,因为尽管您可能正在进行web开发,但回答这个问题并不需要这些知识,而且这个问题与此无关。对不起。我只是在写js网格,忘了这个问题只是关于排序c列表的。@Henk Holterman,因为我们用来排序passsing的person字段作为stringcolumn进行排序。为什么要使用标记?也不需要标记,因为虽然您可能在做web开发,但回答这个问题不需要这些知识,这个问题与此无关。对不起。我只是在写js grid,忘了这个问题只是关于排序c列表的。@Henk Holterman因为我们用来排序passsing的person字段将函数排序为stringcolumn。我喜欢这个,它对我有用,但我意识到我需要按多个字段排序,而不仅仅是一个:我喜欢这个,它对我有用,尽管如此,我意识到我需要按多个字段排序,而不仅仅是一个字段: