[英]Sorting a multi-dimensional [,] array in C#, composed of integers
我有以下数组:
private int[,] testSamples = new testSamples[101,101];
它应该代表一个花名册,列0到100,行0到100。在该花名册中,滴入了各种化学液体。 我正在为此工作的人想要以这样一种方式工作:他可以首先照顾容器中液体最多的容器。
因此,我需要以这种方式取出并打印数据:
testSamples[35,40] = 12
testSamples[11,12] = 11
testSamples[92,14] = 10
testSamples[18,3] = 10
testSamples[1,61] = 7
...
例如。 几天来,我一直在努力思考,在StackoverFlow上我还研究了其他一些问题,但是我无法解决其中的任何问题。
有没有办法做到这一点,还是我应该放弃数组而去换一种容器,例如ArrayLists或List项目?
您可以执行此操作,但是需要一个容器来容纳索引的输出对,一种快速的方法是匿名类型和LINQ:
var sorted = from x in Enumerable.Range(0, testSamples.GetLength(0))
from y in Enumerable.Range(0, testSamples.GetLength(1))
select new {
X = x,
Y = y,
Value = testSamples[x,y]
} into point
orderby point.Value descending
select point;
sorted
是匿名类型的IEnumerable
,每个IEnumerable
都是数组的索引和值。
编辑:把最大的放在首位...
您最好使用OrderedBag之类的东西。 另外,您可能希望List不仅仅是简单地存储Integers。 您似乎要尝试表示一个更复杂的逻辑对象,例如名册,实验,烧杯等。
更新:根据有关SortedList的注释进行编辑,以改用OrderedBag。
这是一个建议,我认为最终与Richard的想法非常相似,但是没有使用LINQ。
编写一个包含三个值的快速结构(可能甚至已经存在):x,y和value。 像这样:
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
对象的任何可排序的一维集合; 我可能会使用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);
}
假设3x3:
5 4 3
2 1 9
8 7 6
您可以将坐标存储在具有关键液体大小,值坐标的SortedDictionary中:
key - value
9 - [2,1]
8 - [0,3]
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.