Reputation: 1569
Is it possible to add items to sorted list with the same value, because when I am trying to do so it shows me an error:
"An entry with the same key already exists."
If it's possible, then how?
Upvotes: 1
Views: 2210
Reputation: 129
You can't insert multiple key with same name but you can insert multiple value using the same object. You don't need to used unique object.
I am showing an example
SortedList sortedList = new SortedList()
{
{ "Ind", "India" },
{ "Inda", "India" },
{ "BD", "Bangladesh" },
{ "SA", "South Africa" },
{"SL", "Sri Lanka" },
{"UAE", "United of Arab Emirates" },
{"USA", "United States of America" }
};
Console.WriteLine("Sorted List Elements");
foreach(DictionaryEntry item in sortedList)
{
Console.WriteLine($"Key: {item.Key}, Value: {item.Value}");
}
Here, I have taken 7 examples. First two are most similar, I have just change the key not the objects. Objects are the are same. I think you got my point.
Upvotes: 0
Reputation: 1907
It is not possible* to add duplicate keys as stated by other users.
In c# you might be able to use the Lookup class instead, which allows multiple values to be stored with the same key.
See: http://msdn.microsoft.com/en-us/library/bb460184.aspx
* It is possible, see comments, but only by defining a comparitor that never returns equality for equal items, which IMO is a really really bad idea.
Upvotes: 3
Reputation: 3393
Define a class that implements IComparer
. When you instantiate the SortedList
, you pass in an instance of your class. Check out Knasterbax's answer.
Upvotes: 0
Reputation: 8337
Key should be unique. See this in MSDN
ArgumentException - An element with the specified key already exists in the SortedList object.
http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.add.aspx
Upvotes: 0