2010-02-02 69 views
3

组成我有以下的数组:排序在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或列表项?

回答

1

这里有一个建议,我认为最终与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); 
} 
+0

它可以工作,但计算输出需要很长时间。 – KdgDev 2010-02-03 07:22:22

+0

解决时间问题:在double for-loop内添加if语句。如果testSamples [i; j]值为0,则不要添加。 – KdgDev 2010-02-03 08:48:21

2

你可能会更喜欢使用类似OrderedBag的东西。此外,您可能希望让您的List存储除了整数之外的其他东西。它看起来像是一个更复杂的逻辑对象,你试图去表现,比如花名册,实验,烧杯等等。

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

+0

'SortedList'将要求密钥是唯一的;我不认为这可以应用在这种情况下。 – 2010-02-02 15:43:37

+0

好点。更新为使用OrderedBag代替。 – Nick 2010-02-02 16:02:59

5

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

编辑:将第一最大...

+0

@迈克尔哈伦:好点...会更新。 – Richard 2010-02-02 15:36:45

+0

Hmz,可以将它放入StringBuilder对象吗? 我的意思是,最终的结果。 – KdgDev 2010-02-03 01:31:49

+0

用StringBuilder,我可以做AppendLine,toString()最终的结果,它可以进入一个文本文件。 对不起,如果我似乎依赖你们有点太多,但我从来没有使用LINQ或IEnumerable之前。我找不到任何方法将此结果转换为字符串。 – KdgDev 2010-02-03 02:06:10

0

假设的3x3:

5 4 3 
2 1 9 
8 7 6 

你可以只存储与关键液体大小在SortedDictionary坐标,坐标值:

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

适用于排序阅读,但不适用于编写新的液体数量来协调x,y。 – 2010-02-02 16:11:18