Sorting a multi-dimensional array [,] in C #, consisting of integers

I have the following array:

private int[,] testSamples = new testSamples[101,101];

It is assumed that it is a list with a column from 0 to 100 and a line from 0 to 100. In these lists, various chemical liquids are discarded. The person I do this with wants to work in such a way that he can take care of the container with the most liquid in it in the first place.

So, I need to get the data and print it like this:

testSamples[35,40] = 12
testSamples[11,12] = 11
testSamples[92,14] = 10
testSamples[18,3] = 10
testSamples[1,61] = 7
...

For instance. I came across this issue several times on this issue, I looked at some other issues here in StackoverFlow, but I can't get them to work.

Is there a way to do this, or should I discard arrays and switch to another kind of container, like ArrayLists or List?

+3
4

, , , , LINQ.

(- ), : x, y . :

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);
}
+1

, , 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 , .

: ...

+5

, , - OrderedBag. , , , . , , , , , , - .

. SortedList OrderedBag.

+2

, 3x3:

5 4 3
2 1 9
8 7 6

SortedDictionary , :

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

Source: https://habr.com/ru/post/1731027/


All Articles