Ton*_*sen 1 c# arrays sorting class blazor
我有一个 void SortTable,我能够根据属性(在本例中为 ticketId)对类实例数组进行排序。
private void SortTable()
{
if (ascending)
{
Array.Sort(tickets,
delegate (TicketData x, TicketData y) { return x.ticketId.CompareTo(y.ticketId); });
} else
{
Array.Sort(tickets,
delegate (TicketData x, TicketData y) { return y.ticketId.CompareTo(x.ticketId); });
}
ascending = !ascending;
}
Run Code Online (Sandbox Code Playgroud)
它有效,但我有一个包含更多要排序的字段的表。我可以通过为表中的每个字段创建空白来解决这个问题。它就像 SortByTicketId()、SortByName() 等。但我想要一个函数来处理这个。
我想写这样的东西:
private void SortTable(sortByThisProperty)
{
Array.Sort(tickets,
delegate (TicketData x, TicketData y) { return x.[sortByThisProperty].CompareTo(y.[sortByThisProperty]); });
}
Run Code Online (Sandbox Code Playgroud)
但是这个伪代码不起作用,我看不出有办法将属性作为参数传递。必须有另一种方法来做到这一点?
为什么不使用 linq 的 OrderBy?
var employees = ....
employees.OrderBy(e => e.Name).ToArray();
Run Code Online (Sandbox Code Playgroud)
但是按照您的方式进行操作的一种方法是使用像 linq 这样的选择器:
private void SortTable<T, Q>(T[] source, Func<T, Q> sortSelector)
where Q: IComparable<Q>
{
Array.Sort(source, (x, y) => sortSelector(x).CompareTo(sortSelector(y)));
});
Run Code Online (Sandbox Code Playgroud)
你会以类似的方式使用它: employees.SortTable(e => e.Name);
归档时间: |
|
查看次数: |
94 次 |
最近记录: |