473,748 Members | 2,602 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SortedList - Sort by VALUE (not KEY)

Hi -

Does anyone know a way to created a SortedList (in the
System.Collecti ons namespace) that will sort on VALUES instead of
KEYS... ?

The scenario is this - I have a SortedList containing key-value pairs
of UserID - DisplayName for a whole bunch of user objects. The UserID
is simply a long, the DisplayName is something like, "Jones, Bill". I
want the SortedList to sort the names alphabetically, rather than by
increasing order of UserIDs.

The simple answer is to use the DisplayName as a key, and UserID as a
value. However this barfs if I have multiple people with the same
DisplayName, as you can't have duplicate keys in a SortedList.

I know that I can override the IComparer that the SortedList uses for
comparisons, however, logistically I cannot think of a way to create
an IComparer that will be able to access the VALUES of the SortedList
collection. The problem is that I MUST supply the IComparer at
construction time of the SortedList; however the IComparer needs to
know about the SortedList so that when it is supplied with 2 keys to
sort, it can then access the values of the collection to work out
which comes before the other. And of course, I can't do something like
this -

SortedList sList = new SortedList(new MyComparer(sLis t));

for (hopefully) obvious reasons...

The other thing I tried was creating a "wrapper class" like this -

class SortedUserList : IComparer {
private SortedList userList = null;

public SortedList UserList {
get {
if (userList == null) {
userList = new SortedList(this );
}

return userList;
}
}

public SortedUserList( ) {
}

#region IComparer Members

public int Compare(object x, object y) {
string first = UserList[x] as string;
string second = UserList[y] as string;

return first.CompareTo (second);
}

#endregion
}

But this also didn't work - I got a Stack Overflow when I tried to add
the second user into the list.

I'm really hoping that there is a simple solution to this problem.

Thanks for your help,
gerrod
Nov 15 '05 #1
1 20545
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

No you can't just pass in a Comparator, because in SortedList, it is
automatically applied to the keys instead of the values, no matter what
you do (and that's the way it is supposed to work anyway...)

An easy way would be to preserve the link between the key and the value
yourself, e.g.: in a struct, like a short program below, and then make
it implement IComparable to sort it based on user names. Then, a simple
ArrayList will do from there (see below)

using System;
using System.Collecti ons;

class MainClass
{
~ public static void Main(string[] args) {
~ ArrayList users = new ArrayList();

~ users.Add(new User(1000, "Set"));
~ users.Add(new User(1004, "List"));
~ users.Add(new User(1002, "Gerrod"));
~ users.Add(new User(1003, "Map"));

~ users.Sort();

~ foreach (User user in users) {
~ Console.WriteLi ne(user.Id + ", " + user.Name);
~ }
~ }
}

struct User : IComparable {
~ private long _id;
~ private string _name;

~ public User(long id, string name) {
~ _id = id;
~ _name = name;
~ }

~ public long Id {
~ get {
~ return _id;
~ }
~ }

~ public string Name {
~ get {
~ return _name;
~ }
~ }

~ public int CompareTo(objec t obj) {
~ if(obj == null) {
~ return 1;
~ }
~ User that = (User)obj;
~ return this._name.Comp areTo(that._nam e);
~ }
}
gerrod wrote:

| Hi -
|
| Does anyone know a way to created a SortedList (in the
| System.Collecti ons namespace) that will sort on VALUES instead of
| KEYS... ?
|
| The scenario is this - I have a SortedList containing key-value pairs
| of UserID - DisplayName for a whole bunch of user objects. The UserID
| is simply a long, the DisplayName is something like, "Jones, Bill". I
| want the SortedList to sort the names alphabetically, rather than by
| increasing order of UserIDs.
|
| The simple answer is to use the DisplayName as a key, and UserID as a
| value. However this barfs if I have multiple people with the same
| DisplayName, as you can't have duplicate keys in a SortedList.
|
| I know that I can override the IComparer that the SortedList uses for
| comparisons, however, logistically I cannot think of a way to create
| an IComparer that will be able to access the VALUES of the SortedList
| collection. The problem is that I MUST supply the IComparer at
| construction time of the SortedList; however the IComparer needs to
| know about the SortedList so that when it is supplied with 2 keys to
| sort, it can then access the values of the collection to work out
| which comes before the other. And of course, I can't do something like
| this -
|
| SortedList sList = new SortedList(new MyComparer(sLis t));
|
| for (hopefully) obvious reasons...
|
| The other thing I tried was creating a "wrapper class" like this -
|
| class SortedUserList : IComparer {
| private SortedList userList = null;
|
| public SortedList UserList {
| get {
| if (userList == null) {
| userList = new SortedList(this );
| }
|
| return userList;
| }
| }
|
| public SortedUserList( ) {
| }
|
| #region IComparer Members
|
| public int Compare(object x, object y) {
| string first = UserList[x] as string;
| string second = UserList[y] as string;
|
| return first.CompareTo (second);
| }
|
| #endregion
| }
|
| But this also didn't work - I got a Stack Overflow when I tried to add
| the second user into the list.
|
| I'm really hoping that there is a simple solution to this problem.
|
| Thanks for your help,
| gerrod
- --
Ray Hsieh (Djajadinata)
ray underscore usenet at yahoo dot com
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (MingW32)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQE/nIkiwEwccQ4rWPg RAqn+AJ402SGneg A2+hvAOFQf+3Pvf I5yiQCfYAk4
cXPzlQMWMVXcpDb SsNK103w=
=tjwy
-----END PGP SIGNATURE-----

Nov 15 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6194
by: Johannes | last post by:
I've read that the SortedList object can sort its elements in alphabetical or numerical order. If this is correct, how can I set the sort order to numerical. Regardless of the key/value pairs I add to the list, it only seems to sort alphabetically. Thanks
1
1539
by: Vai2000 | last post by:
Hi All, Is there a way to custom sort the SortedList by its value...I know how to do with keys by passing a special Comparable Class...but how do I sort it based on Values? TIA
3
2817
by: Michael C | last post by:
Hi all, I'm using a SortedList to store data, and want the keys to be compared in case insensitive order, so that mySList is the same as mySList
6
1876
by: Jose Jarabo | last post by:
Hello, thanks in advance for any and all replies. I am not sure how to categorize this, either a bug or something else but here is my problem. I am testing with 2 elements on a sorted list. If I remove the last element on the list everything works fine and I can add other elements to it. However if I remove the first element on the list and I try to add something then my first element is changed when I add a new element to that new...
2
3079
by: Pekka | last post by:
Could somebody say why the piece of code below does not work? My purpose is to renumber keys in a SortedList (after removal of an item) so that the keys would always contain an unbroken sequence of integers starting with 1. For some reason this is not the result. IDictionaryEnumerator dictEnum = sortedList.GetEnumerator(); int i=1; while ( dictEnum.MoveNext() ) { DictionaryEntry de = (DictionaryEntry) dictEnum.Current;
6
1538
by: Antonio Paglia | last post by:
Hello. I have tried to insert this items into a SortedList. dic = New SortedList dic.Add("<<", "<<") dic.Add("==", "==") dic.Add(">>", ">>") dic.Add("@@", "@@") dic.Add("??", "??") Debugging this peace of code I have notice that '??' appears as first item,
4
6766
by: semedao | last post by:
Hi, I want to implement list of key-values that can be sort by 2 ways. let's say that in the first step I wanted to make SortList based on Key = int index that cannot change and Value is another SortedList like this: class OtherSortedList : SortedList { ..... int GetTotalAmountOfAllItems().... }
1
3904
by: raylopez99 | last post by:
I seem to get name collision between the Generic collection SortedList and C++.NET Framework collection SortedList. How to resolve? Here are the libraries that seem to clash: System::Collections::SortedList, System::Collections::Generic::SortedList, using namespace System::Collections; using namespace System::Collections::Generic; Below is a working version of the generic template SortedList, which
3
4474
dcharnigo
by: dcharnigo | last post by:
I thought I would be tricky and force the SortedList to not sort using a custom IComparer, I used the following code, but when the list is sorting using the custom sort the accessors become unusable and throw exceptions. I have since discovered that the accessors use the IComparer to find things and since it is set at -1 it gets a null return value, however the foreach loops dont use it. I must preserve the insert order, I don't want the...
0
8984
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9238
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8237
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4593
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2775
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.