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?
Asked
Active
Viewed 2,102 times
1

Brezhnews
- 1,559
- 2
- 20
- 37
-
possible duplicate of [C# Sortable collection which allows duplicate keys](http://stackoverflow.com/questions/5716423/c-sharp-sortable-collection-which-allows-duplicate-keys) – Tim Partridge Sep 15 '15 at 17:05
4 Answers
3
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.

sji
- 1,877
- 1
- 13
- 28
-
It's possible. See [Knasterbax's answer](http://stackoverflow.com/a/21886340/224976) to a similar question – Tim Partridge Sep 15 '15 at 17:03
-
That solution breaks a precondition of the container (that two equal keys will return equality), and as commenters have pointed out that introduces a raft of other problems. Best to use the container intended for use in this fashion IMO. That said I will update my answer. – sji Sep 16 '15 at 09:55
-
Good point. The comments in Kasterbax's answer reveal some caveats – Tim Partridge Oct 15 '15 at 14:49
1
No, it's not possible. The keys must be unique.

Andrew Cooper
- 32,176
- 5
- 81
- 116
-
It's possible. See [Knasterbax's answer](http://stackoverflow.com/a/21886340/224976) to a similar question – Tim Partridge Sep 15 '15 at 17:03
-
0
Define a class that implements IComparer
. When you instantiate the SortedList
, you pass in an instance of your class. Check out Knasterbax's answer.

Community
- 1
- 1

Tim Partridge
- 3,365
- 1
- 42
- 52
0
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

PraveenVenu
- 8,217
- 4
- 30
- 39
-
It's possible. See [Knasterbax's answer](http://stackoverflow.com/a/21886340/224976) to a similar question – Tim Partridge Sep 15 '15 at 17:03