排序在C#中的多维[,]数组,整数组成 [英] Sorting a multi-dimensional [,] array in C#, composed of integers
问题描述
我有以下数组:
private int[,] testSamples = new testSamples[101,101];
它应该重新present名册,其列0至100和行0至100。在该名册,各种化学液体被丢弃。我这样做的人,希望以这样的方式,他可以先照顾容器的最液体在里面工作。
It's supposed to represent a roster, with column 0 to 100 and row 0 to 100. In this rosters, various chemical liquids are dropped. The person I'm doing this for wants to work in such a way that he can take care of the container with the most liquid in it first.
所以,我需要出去获取数据,并以这种方式印刷的:
So, I need to get the data out and printed in this manner:
testSamples[35,40] = 12
testSamples[11,12] = 11
testSamples[92,14] = 10
testSamples[18,3] = 10
testSamples[1,61] = 7
...
有关实例。
我一直在破解我的头在这个几天,我一直看着这里的一些其他问题在计算器上,但我不能让任何人来工作。
For instance. I've been cracking my head over this for a few days, I've looked into some other questions here on StackoverFlow, but I can't get any of them to work.
有没有办法做到这一点,或者我应该放弃阵列和去为另外一种容器,像的ArrayList或列表项目?
Is there a way to do this, or should I give up on arrays and go for another sort of container, like ArrayLists or List items?
推荐答案
下面是我想最终是神似理查德的一个建议,但不使用LINQ。
Here's a suggestion that I think ends up being quite similar to Richard's, but without using LINQ.
写一个快速结构(这样的事情,甚至可能已经存在),它包含三个值:X,Y和价值。像这样的:
Write a quick struct (something like this may even exist already) that includes three values: x, y, and value. Like this:
public struct SampleSlot : IComparable<SampleSlot> {
public int X;
public int Y;
public int Value;
public SampleSlot(int x, int y, int value) {
X = x;
Y = y;
Value = value;
}
public int CompareTo(SampleSlot other) {
return Value.CompareTo(other.Value);
}
}
然后你可以折叠的 INT [,]
数组 SampleSlot
中的任何可排序的一维的对象集合你喜欢;我可能会用走列表与LT; SampleSlot&GT;
:
Then you can collapse your int[,]
array into any sortable one-dimensional collection of SampleSlot
objects you like; I'd probably go with a List<SampleSlot>
:
List<SampleSlot> slotsList = new List<SampleSlot>();
for (int i = 0; i < testSamples.GetLength(0); ++i) {
for (int j = 0; j < testSamples.GetLength(1); ++j) {
slotsList.Add(new SampleSlot(i, j, testSamples[i, j]));
}
}
slotsList.Sort();
// assuming you want your output in descending order
for (int i = slotsList.Count - 1; i >= 0; --i) {
SampleSlot slot = slotsList[i];
Console.WriteLine("testSamples[{0},{1}] = {2}", slot.X, slot.Y, slot.Value);
}
这篇关于排序在C#中的多维[,]数组,整数组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!