是否可以将具有相同值的项目添加到排序列表中,因为当我尝试这样做时,它会显示错误:
“具有相同密钥的条目已存在。”
如果可以的话,怎么样?
不可能*按照其他用户的说明添加重复的密钥。
在 c# 中,您可能可以使用 Lookup 类,它允许使用同一键存储多个值。
请参阅:http://msdn.microsoft.com/en-us/library/bb460184.aspx
* 这是可能的,请参阅评论,但只能通过定义一个永远不会返回相等项的比较器来实现,在我看来,这是一个非常非常糟糕的主意。
不,这是不可能的。密钥必须是唯一的。
密钥应该是唯一的。在 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
您不能插入多个具有相同名称的键,但可以使用同一对象插入多个值。您不需要使用唯一的对象。
我正在展示一个例子
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}");
}
这里我举了7个例子。前两个最相似,我只是更改了键而不是对象。对象是相同的。 我想你明白我的意思了。