Solved

Help!! Sort Hashtable value

Posted on 2004-10-12
11
3,559 Views
Last Modified: 2012-06-27
I need to sort my hashtable by locationName.  I'm using both values cityCode and locationName in my code.  And locationName can be duplicated.

Hashtable cities=new Hashtable();
//SortedList slist = new SortedList();

for(int i=0, j=1;i<total;i++,j++)
{
      string cityCode=list.GetLocation(i).Code;
      string locationName=list.GetLocation(i).Location;
      
      if(!cities.ContainsKey(cityCode))
      {
            //slist.Add(locationName, cityCode);
            cities.Add(cityCode, locationName);
      }
}

ANY HELP APPRECIATED!!! THANKS!!!
0
Comment
Question by:sticar
  • 4
  • 4
  • 3
11 Comments
 
LVL 7

Expert Comment

by:NipNFriar_Tuck
Comment Utility
Alright create a comparer class like

    class HTComparer : IComparer {
        #region IComparer Members

        public int Compare(object x, object y) {
            // TODO:  Add HTComparer.Compare implementation
            return 0;
        }

        #endregion

    }

Then set the comparer to the hashtable comparer

Hashtable ht = new Hashtable();
ht.comparer = new HTComparer();

If you need help implementing the compare function let me know...
0
 

Author Comment

by:sticar
Comment Utility
Yes I definitely need help... :)
0
 
LVL 7

Expert Comment

by:NipNFriar_Tuck
Comment Utility
Realize that object x and object y are just the key values(strings) being passed in and since you are passing in a string you could write something like:

        public int Compare(object x, object y) {
            // TODO:  Add HTComparer.Compare implementation
            return String.Compare( x.ToString(), y.ToString() );
        }
0
 
LVL 14

Expert Comment

by:AvonWyss
Comment Utility
Er. Why aren't you using a SortedList instead of a Hashtable? This might be what you need, it also offers dictionary fonctionality but it's always sorted. Performance is also quite good (not as fast as a Hashtable, but faster than needing to sort the hashtable contents afterwards).
0
 

Author Comment

by:sticar
Comment Utility
AvonWyss: I would still have the issue with sorting the "values" instead of the keys right?  And I can't add the Value as the Key because they can be duplicated.  

NipNFriar_Tuck:
I created a class above named HTComparer.cs

Then in another .ascx.cs file I try to call it:
Hashtable cities= new Hashtable();
cities.comparer   //There isn't a "comparer" as an option.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 14

Accepted Solution

by:
AvonWyss earned 500 total points
Comment Utility
Well, you could work with a SortedList which does not contain strings but lists. This wouls allow you to use Value as key and have multiple associated values.

But there might be another, simpler solution. Try this:

string[] cities=new string[total];
string[] locations=new string[total];
for(int i=0; i<total; i++) {
     cities[i]=list.GetLocation(i).Code;
     location[i]=list.GetLocation(i).Location;
}
Array.Sort(locations, cities);

This sort by location and also does the same array operations on cities, so that the pairs still match.

Another solution could be to implement your own comparer for the objects or structs returned by GetLocation(), then you could have them in a normal array or an ArrayList. Many possibilities here...
0
 
LVL 7

Expert Comment

by:NipNFriar_Tuck
Comment Utility
Sorry, I was a little off on the implementation...

do

Hashtable ht = new Hashtable( null, new HTComparer() );

during the constructor...
0
 

Author Comment

by:sticar
Comment Utility
Does this look close to right? I'm not sure on the sort area, it's only comparing the two values passed in, not all the values in locationName.
--------------------------------------------------------------------
                        HTComparer cities = new HTComparer();
                        HTComparer sort = new HTComparer();

                        for(int i=0;i<total;i++)
                        {
                              string cityCode=list.GetLocation(i).Code;
                              string locationName=list.GetLocation(i).Location;

                              if(!cities.ContainsKey(locationName))
                              {
                                    sort.Compare(cityCode, locationName);
                                            cities.Add(cityCode, locationName);
                              }
                        }
                        

my class
--------------------------------------------------------------------
      public class HTComparer :IComparer
      {
            public HTComparer()
            {
                  Hashtable ht = new Hashtable( null, new HTComparer());
            }

            public int Compare(object x, object y)
            {
                  return String.Compare( x.ToString(), y.ToString() );
            }
      }
0
 

Author Comment

by:sticar
Comment Utility
AvonWyss, I ended up using yours.  It works great!  Thanks!
0
 
LVL 7

Expert Comment

by:NipNFriar_Tuck
Comment Utility
sticar, your last post was close... here is what it should have looked like...
--------------------------------------------------------------------
                    Hashtable cities = new Hashtable( null, new HTComparer() );
 
                    for(int i=0;i<total;i++)
                    {
                         string cityCode=list.GetLocation(i).Code;
                         string locationName=list.GetLocation(i).Location;

                         if(!cities.ContainsKey(locationName))
                         {
                             cities.Add(cityCode, locationName);
                         }
                    }
                   

my class
--------------------------------------------------------------------
     public class HTComparer :IComparer
     {
          public int Compare(object x, object y)
          {
               return String.Compare( x.ToString(), y.ToString() );
          }
     }

Since a Hashtable sorts keys automagically you do not need to explicitly sort the Hashtable!  The keys are sorted via the comparer that you gave during instantiaion.  By the by this is the alternate solution that AvonWyss gave...  Cheers.
0
 
LVL 14

Expert Comment

by:AvonWyss
Comment Utility
NipNFriar_Tuck, since the values must be sorted, not the keys, you suggestion does not solve this problem. Also, note that the hashtable is not sorted by the comparer you gave. It's primary sorting key is the hash code, and for two items which land in the same bucket (that is, where the hashcode modulus the number of buckets is equal), they are sorted with the comparer so that the bucket can be searched with a binary search. But your suggestion with the comparer would work fine for a SortedList, if there wasn't that issue with the multiple values with the same value.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now