pedro jorge
pedro jorge

Reputation: 47

Sort 2 dimensional array based on the value in one row

I have data like

1   3   9   2   7   8   9
120 70  76  190 300 50  40

how can I sort the array based on the second row and return the value of the max number from the first row. I mean, the output become >

7    2    1    9   3   8   9
300  190  120  76  70  50  40

And I get the 7 as output.

Upvotes: 0

Views: 90

Answers (2)

wmz
wmz

Reputation: 3685

If you'd like to know the answer to 'what's the max number now' (or to put it differently, to keep the order rather then sort it post processing - beware it has a performance penalty!) then SortedList may come in handy:

        int[] a = { 1, 3, 9, 2, 7, 8, 9 };
        int[] b = { 120, 70, 76, 190, 300, 50, 40 };

        var sortedList = new SortedList<int,int>();
        for (int i = 0; i < a.Length; i++)
        {
            sortedList[b[i]] = a[i];        
        }
        Console.WriteLine(sortedList.Last().Value);    

(if you want to see what's current max value as you add data just move WriteLine to inside of the loop)

Upvotes: 0

Bradford Dillon
Bradford Dillon

Reputation: 1800

First I would get your data out of the rectangular array into something a bit more usable. To do this, first convert the data into a List<Tuple<int, int>> because it is much easier to work with.

int[,] rawData = { { 1, 3, 9, 2, 7, 8, 9 }, { 120, 70, 76, 190, 300, 50, 40 } };
var data = new List<Tuple<int, int>>();

for(int i = 0; i < rawData.GetLength(1); i++)
{
    data.Add(new Tuple<int, int>(rawData[0, i], rawData[1, i]));
}

Then it is just a matter of using a Linq query to get the data you want.

var result = data.OrderByDescending(x => x.Item2).First().Item1;

Fiddle

Upvotes: 1

Related Questions