2

I have been having a nagging problem for a few days, here's what I'm trying to do:

I am writing a program that manipulates various set of numbers in multiple ways and so far so good- now I control one of such computations using a loop, so that each time it goes round it outputs an int value x and an int value y.

Now x is sequential, being derived from a counter, y is just a variable number.

So I repeat I have a simple loop reading the datarows

foreach (DataRow dr in dTable.Rows)
{
....
I output x and y (after some calculations)
....
}

Now I would like to get this two values for each row and at the end do a sort based on value y! Originally I was simply going to use a hashmap like I used to do in java and do a sort by value, but I am finding it hard to do in c# as the datadictionary (I don't want to use a temp table either) only allows you sorting by key (in my case x)

Now what approach should I take? - Use the output pair values of my loop as the input for a datatable? - Use a 2d array which looks pretty complex but eventually is the only way to maintain the pair relation between x and y?

Or is there any other way to do do the equivalent of a java hashmap sorting by value?

Sathyajith Bhat
  • 21,321
  • 22
  • 95
  • 134
Mick
  • 21
  • 1

3 Answers3

2

If the y values are unique, then maybe:

var list = new SortedList<YType, XType>();
... Loop ...
     list.Add(yValue, xValue);

This is then both keyed and sorted by the y values, but the keys must be unique.

To make things more complicated, SortedDictionary<,> is also keyed and sorted; some minor differences in the O though - whether add or fetch is cheapest etc.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

Make a class to represent your data pair and store all the pairs in a list of some kind. Implement IComparable to sort on the second value, and sort it in the usual manner (example in Java, but should be easily translatable to C#):

class DataPair implements Comparable { 
     int x;
     int y;

     public int compareTo(DataPair o) {
         return y - o.y;
     }
}

Make a list of DataPairs, and sort it with the library API's when you're done. Your implementation of the comparison-function should give you whatever result you want.

bjornars
  • 1,506
  • 2
  • 10
  • 13
  • Would you mind being more specific ? if I store the pairs in a list i will loose the coupling between key and value! – Mick Feb 11 '11 at 14:37
0

I would use LINQ to do this type of manipulation, not using map-type data structures at all:

var list = from dr in dTable.Rows
           let x = ComputeX(dr)
           let y = ComputeY(dr)
           orderby y
           select new { x, y };
Gabe
  • 84,912
  • 12
  • 139
  • 238