【问题标题】:How to auto-increment a key of a Dictionary?如何自动增加字典的键?
【发布时间】:2012-01-20 22:23:31
【问题描述】:

我正在用 C# 制作应用程序。在我的应用程序中,我使用了以下结构的Dictionary

Dictionary<int, string> DataDictionary1 = new Dictionary<int, string>();

这里我希望字典中的键值应该是自动递增的。为此,我将逻辑用作:

 string header="ABC";
 int maxKey = DataDictionary1 .Max(x => x.Key);
 DataDictionary1 .Add(maxKey + 1, header);

这是一种有效的方法,因为我想连续进行此操作。有没有比这种方式更快的方式?

【问题讨论】:

  • 不使用max,直接访问最后一个索引(int maxKey = DataDictionary1.Values[DataDictionary1.Length -1].Key); ) 还要确保有物品
  • @Polity 你不能索引System.Collections.Generic.Dictionary&lt;K, V&gt; 的值集合。

标签: c# dictionary max auto-increment


【解决方案1】:

你为什么不直接使用List&lt;string&gt; 然后向其中添加元素。列表中元素的索引将代表 Key。所以:

List<string> myList = ...

然后:

string header = "ABC";
myList.Add(header);

【讨论】:

  • 谢谢 但是你能告诉我是否可以从特定索引列表中访问一个项目?
  • @Dany:是的。 string someValue = myList[1];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-31
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多