I have a set of elements/keys which I'm reading from two different config files. So the keys may be same but with different values associated with each of them.
I want to list them in the sorted order. What can I do ? I tried with SortedList
class but it does not allow duplicate keys.
How can I do it?
e.g Lets say I have 3 elements with keys 1,2,3. Then i get one more element having key 2 (but different value). Then I want the new key to get inserted after existing key 2 but before 3. If I againg find an element with key 2, then it should go after most recently added key 2.
Please note than I'm using .NET 2.0
A SortedList does not allow duplicate keys. Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting. Elements in this collection can be accessed using an integer index.
keys cannot be duplicate by definition. What you are talking about is called a compound key (made up of several values). So this means you can use a regular map as long as you use a key that combines both values.
Remarks. The SortedSet<T> class does not accept duplicate elements. If item is already in the set, this method returns false and does not throw an exception.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .
I prefer to use LINQ for this type of thing:
using System.Linq;
...
var mySortedList = myList.Orderby(l => l.Key)
.ThenBy(l => l.Value);
foreach (var sortedItem in mySortedList) {
//You'd see each item in the order you specified in the loop here.
}
Note: you must be using .NET 3.5 or later to accomplish this.
what you need is a Sort function with a custom IComparer. What you have now is the default icomparer when you use sort. this will check on a field value.
When you create a custom IComparer (you do this in you class by implementing the Icomparable interface). what it does is: your object checks itself to every other object in the list you sort.
this is done by a function. (don't worry VS will implementd it when refering your interface
public class ThisObjectCLass : IComparable{
public int CompareTo(object obj) {
ThisObjectCLass something = obj as ThisObjectCLass ;
if (something!= null)
if(this.key.CompareTo(object.key) == 0){
//then:
if .....
}
else if(this.value "is more important then(use some logic here)" something.value){
return 1
}
else return -1
else
throw new ArgumentException("I am a dumb little rabid, trying to compare different base classes");
}
}
read on the links above for better information.
I know I had some troubles understanding this myself in the beginning, so for any extra help add a comment and I will elaborate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With