首页 \ 问答 \ 根据数值差异对数组进行排序(Sort Array on on Value Difference)

根据数值差异对数组进行排序(Sort Array on on Value Difference)

例如,我有一个数组

string[] stArr= new string[5] { "1#3", "19#24", "10#12", "13#18", "20#21" };

我想对这个数组进行排序

3-1=2;
24-19=5;
12-10=2;
18-13=5;
21-20=1;

排序结果应该是这样的

string[] stArr= new string[5] { "20#21", "1#3", "10#12", "13#18", "20#21" };

我必须为所有可能的情况找到解决方案。

1>数组的长度不固定(数组中的元素)

2> y总是大于x, eg x#y

3>我不能使用列表


I Have An Array,for example

string[] stArr= new string[5] { "1#3", "19#24", "10#12", "13#18", "20#21" };

i want to sort this array on

3-1=2;
24-19=5;
12-10=2;
18-13=5;
21-20=1;

and the sorting result should be like

string[] stArr= new string[5] { "20#21", "1#3", "10#12", "13#18", "20#21" };

I have to find the solution for all possible cases.

1>length of the array is not fixed(element in the array)

2>y always greater than x e.g x#y

3> i can not use list


原文:https://stackoverflow.com/questions/33460834
更新时间:2023-10-28 15:10

最满意答案

您应该改用SortDescriptions集合。 此集合允许您提供如何在视图中对项目进行排序的一组规则。

你可以在这里找到一个很好的例子来说明如何使用它: https : //stackoverflow.com/a/19952233/6597895

public static void SortDataGrid(DataGrid dataGrid, int columnIndex = 0, ListSortDirection sortDirection = ListSortDirection.Ascending)
{
    var column = dataGrid.Columns[columnIndex];

    // Clear current sort descriptions
    dataGrid.Items.SortDescriptions.Clear();

    // Add the new sort description
    dataGrid.Items.SortDescriptions.Add(new SortDescription(column.SortMemberPath, sortDirection));

    // Apply sort
    foreach (var col in dataGrid.Columns)
    {
        col.SortDirection = null;
    }
    column.SortDirection = sortDirection;

    // Refresh items to display sort
    dataGrid.Items.Refresh();
}

You should work with SortDescriptions collection instead. This collection allows you to provide set of rules of how to sort items in the view.

You can find a good example on how to use it here: https://stackoverflow.com/a/19952233/6597895

public static void SortDataGrid(DataGrid dataGrid, int columnIndex = 0, ListSortDirection sortDirection = ListSortDirection.Ascending)
{
    var column = dataGrid.Columns[columnIndex];

    // Clear current sort descriptions
    dataGrid.Items.SortDescriptions.Clear();

    // Add the new sort description
    dataGrid.Items.SortDescriptions.Add(new SortDescription(column.SortMemberPath, sortDirection));

    // Apply sort
    foreach (var col in dataGrid.Columns)
    {
        col.SortDirection = null;
    }
    column.SortDirection = sortDirection;

    // Refresh items to display sort
    dataGrid.Items.Refresh();
}

相关问答

更多
  • 你正在覆盖HeaderStyle。 只需使用默认样式并调整其他部分: