457,953 Members | 1,524 Online Need help? Post your question and get tips & solutions from a community of 457,953 IT Pros & Developers. It's quick & easy.

# Array find and sort

 P: n/a Hi, I need to add this inside an array: 1 3 2 4 3 2 4 5 5 1 I think of using this: Int32[,] myValues; Now I want to find a value (index) in the first colomn. Let's say I'm looking for value 3, the find result will be 3. After that I want to sort the array bases on the values in column two. How can I do that? Thanks! Nov 17 '05 #1
4 Replies

 P: n/a Whoops... "...result will be 3." must be "...result will be 2." And "...array bases on..." should be "...array based on..." Nov 17 '05 #2

 P: n/a Arjen wrote: Whoops... "...result will be 3." must be "...result will be 2." And "...array bases on..." should be "...array based on..." You are looking for a map implementation. There are lots of them. A simplistic approach might be... public class Map { public int _key; public int _val; public Map(int key, int val) { _key = key; _val = val; } public bool Match( int val ) { return _key == val; } } // Then to add and search... ArrayList al = new ArrayList(); al.Add( new Map(1,3) ); al.Add( new Map(2,4) ); al.Add( new Map(3,2) ); // Find an entry for 3. int retVal = -1; for ( int i=0; i

 P: n/a What you want to do is use a Hashtable to store a key value. I didnt test it. But I don't see why it shouldn't work. public struct KeyValue { public KeyValue(int key, int value) { Key = key; Value = value; } public int Key; public int Value; } public class MyComparer : IComparer { int IComparer.Compare(Object x, Object y) { KeyValue keyValueLeft = (KeyValue) x; KeyValue keyValueRight = (KeyValue) y; return((new CaseInsensitiveComparer()).Compare(keyValueRight.V alue, keyValueLeft.Value)); } } public void test() { ArrayList array = new ArrayList(); array.Add(new KeyValue(1,3)); array.Add(new KeyValue(2,4)); array.Add(new KeyValue(3,2)); array.Add(new KeyValue(4,5)); array.Add(new KeyValue(5,1)); array.Sort(new MyComparer()); Hashtable table = new Hashtable(); foreach(KeyValue keyValue in array) table.Add(keyValue.Key, keyValue.Value); //Here we look for keys.... Console.WriteLine(table); // the return object is "2"; //The hastable was already loaded with sorted Key Values by the second colum. foreach(int i in table.Keys) Console.WriteLine("Key:" + i + " Value:" + table[i]); //It should shows //Key: 5 Value: 1 //Key: 3 Value: 2 //Key: 1 Value: 3 //Key: 2 Value: 4 //Key: 4 Value: 5 } Gustavo. "Arjen" wrote in message news:dc**********@news4.zwoll1.ov.home.nl... Hi, I need to add this inside an array: 1 3 2 4 3 2 4 5 5 1 I think of using this: Int32[,] myValues; Now I want to find a value (index) in the first colomn. Let's say I'm looking for value 3, the find result will be 3. After that I want to sort the array bases on the values in column two. How can I do that? Thanks! Nov 17 '05 #4 