【问题标题】:How do I sort jagged array by row in C#?如何在 C# 中按行对锯齿状数组进行排序?
【发布时间】:2011-12-31 00:46:23
【问题描述】:

我有二维锯齿状数组。我想按任何行对其进行排序。

我已经搜索并找到了按列排序的代码

private static void Sort<T>(T[][] data, int col) 
{ 
    Comparer<T> comparer = Comparer<T>.Default;
    Array.Sort<T[]>(data, (x,y) => comparer.Compare(x[col],y[col])); 
}

我可以调整它以按任何行排序吗?

感谢任何帮助。

我的锯齿状数组示例(已添加)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 10;
            int[][] capm = new int[3][];
            for (int i = 0; i <= 2; i++)
            {
                capm[i] = new int[n + 1];
            }
            Random rand = new Random();            
            for (int i = 1; i <= n; i++)
            {
                capm[1][i] = i;
            }

            for (int i = 1; i <= n; i++)
            {
                capm[2][i] = rand.Next(1, 6);
            }

            Sort(capm, 2);

            Console.ReadLine();
        }
            private static void Sort<T>(T[][] data, int col)    
            {  
                data = data.OrderBy(i => i[col]).ToArray();
            }
        }

    }

@Dani & @Martin 我希望我的锯齿状数组按 capm[2][] 排序。

【问题讨论】:

    标签: c# sorting row jagged-arrays


    【解决方案1】:

    鉴于您使用的是锯齿状数组,这将按第 3 项对其进行排序。但是如果您想保证每行具有相同的列数,则二维数组可能会更好...如果您在其中有一个数组没有第三列的数组,这将失败!

    private static void Sort<T>(T[][] data, int col)    
    {  
        data = data.OrderBy(i => i[col]).ToArray();
    }
    

    编辑:

    为了对新的数据引用做任何事情,您要么需要返回它,要么通过引用传递参数:

    private static void Sort<T>(ref T[][] data, int col)    
    {  
        data = data.OrderBy(i => i[col]).ToArray();
    }
    

    数组本身没有排序,创建一个新的排序数组

    【讨论】:

    • 你需要给我更多的细节才能帮助我。我测试了它,它工作正常,除非我误解了你期望的结果。
    • 可能我不清楚给你举个例子。请再次查看问题。我已经添加了一个锯齿状数组的样本。
    【解决方案2】:

    我能想到的唯一方法是按索引数组排序:

    private static void Sort<T>(T[][] data, int row) 
    {
        int[] Indices = new int[data[0].Length];
        for(int i = 0; i < Indices.Length; i++)
            Indices[i] = i;
    
        Comparer<T> comparer = Comparer<T>.Default;
        Array.Sort(Indices, (x, y) => comparer.Compare(data[row][x], data[row][y]);
    
        for(int i = 0; i < data.Length; i++)
        {
            T[] OldRow = (T[])data[i].Clone();
            for(int j = 0; j < OldRow.Length; j++)
                data[i][j] = OldRow[i][Indices[j]];
        }
    }
    

    【讨论】:

    • 我想按仅选择的行对整个数组进行排序。不想对每一行进行排序。
    • @stereo:你的意思是像根据行对表格的列进行排序?
    • @Dani:是的,我想根据行对表格的列进行排序。
    • @stereo:那么它们都必须具有相同的长度......那为什么它是锯齿状数组?
    • @Dani:长度相同,对。我使用锯齿数组,因为我听说如果我使用它会很容易排序。
    猜你喜欢
    • 2023-01-10
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2020-12-21
    • 2016-08-08
    • 2011-03-27
    相关资源
    最近更新 更多