我试图使用IComparer在C#中比较一个2D数组但是不能从我的角度编译代码在sort方法中ab被认为是一个jagad数组而不是一个普通的数组。任何人都知道如何解决那个
int[,] ab = new int[3, 4]
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 2, 3, 4, 5 }
};
Array.Sort<int[]>(ab, new ComparerTwoDArray());
foreach (var i in ab)
{
Console.WriteLine(i);
}
class ComparerTwoDArray : IComparer<int[]>
{
int ix;
public int Compare(int[] x, int[] y)
{
return x[0].CompareTo(y[0]);
}
}
答案 0 :(得分:0)
您没有使用正确的方法:https://msdn.microsoft.com/en-us/library/system.array.sort%28v=vs.110%29.aspx
Array.Sort方法:对一维数组中的元素进行排序。
您可以使用List<List<int>>
然后使用其Sort
LINQ扩展名,例如:
list.Sort((x,y) => x[0].CompareTo(y[0]));
答案 1 :(得分:0)
不幸的是,多维数组是一个非常静态的野兽。您可以通过提供n维坐标(例如,在3d数组中的array[2,8,4]
)轻松访问其中的单个元素,但您无法访问任何整个区域(如行,列,矩形等)。
如果您确实需要进行这种重新排序,则不应将数据保存在多维数组中。而是将其放入锯齿状数组或列表列表中,甚至是4维稀疏矩阵的IReadOnlyDictionary<int, IReadOnlyDictionary<int, IReadOnlyDictionary<int, int>>>
。在这种情况下,你可以很容易地为每个维度编写一个比较器。
在您的情况下,您只需要List<IReadOnlyList<int>>
和IComparer<IReadOnlyList<T>>
之类的内容,可以像这样实现:
public class ListComparer<T> : IComparer<IReadOnlyList<T>>
{
public static readonly IComparer<IReadOnlyList<T>> Default = new ListComparer<T>();
private readonly bool _checkCount;
private readonly int _numberOfElementsToCompare;
private readonly IComparer<T> _elementComparer;
public ListComparer()
: this(true, 1, Comparer<T>.Default)
{
}
public ListComparer(
bool checkCount,
int numberOfElementsToCompare,
IComparer<T> elementComparer)
{
_checkCount = checkCount;
_numberOfElementsToCompare = numberOfElementsToCompare;
_elementComparer = elementComparer
?? throw new ArgumentNullException(nameof(elementComparer));
}
public int Compare(IReadOnlyList<T> x, IReadOnlyList<T> y)
{
if (ReferenceEquals(x, y))
return 0;
if (ReferenceEquals(x, null))
return -1;
if (ReferenceEquals(y, null))
return 1;
if (_checkCount)
{
var diff = x.Count.CompareTo(y.Count);
if (diff != 0)
return diff;
}
return x.Take(_numberOfElementsToCompare)
.Zip(y, (i, j) => _elementComparer.Compare(i, j))
.SkipWhile(value => value == 0)
.FirstOrDefault();
}
}
将被使用:
var matrix = new List<IReadOnlyList<int>>
{
{ new List<int> { 1, 2, 3, 4 } },
{ new List<int> { 5, 6, 7, 8 } },
{ new List<int> { 2, 3, 4, 5 } }
};
matrix.Sort(ListComparer<int>.Default);
foreach (var item in matrix)
{
Console.WriteLine(String.Join(", ", item));
}