Sorting set of pairs of numeric values - is there a .NET equivalent to a hashmap in java?

576 views Asked by At

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?

3

There are 3 answers

0
Marc Gravell On

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.

1
bjornars On

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.

0
Gabe On

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 };