在C#中对多维数组进行排序,由整数组成

我有以下数组:

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 items?

这是一个建议,我认为最终与理查德非常相似,但没有使用LINQ。

写一个快速结构(这样的东西甚至可能存在),包括三个值:x,y和value。 像这样:

 public struct SampleSlot : IComparable { 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

 List slotsList = new List(); 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); } 

您可以这样做,但是您需要一个容器来保存输出索引对,快速执行此操作的方法是匿名类型和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 ,每个类型都是数组的索引和值。

编辑:放最大的……

使用OrderedBag之类的东西可能会更好。 此外,您可能希望让List存储除了Integers之外的其他内容。 看起来你想要代表一个更复杂的逻辑对象,比如名册,实验,烧杯或其他东西。

更新:根据有关SortedList的注释进行编辑,以改为使用OrderedBag。

我们假设3×3:

 5 4 3 2 1 9 8 7 6 

您可以将坐标存储在SortedDictionary中,其中包含关键的液体大小,值坐标:

 key - value 9 - [2,1] 8 - [0,3] ...