简体   繁体   中英

How to auto-increment a key of a Dictionary?

I am making application in C#. In my application I am using Dictionary of following structure:

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

Here I want the key value in dictionary should be auto increment. For that I am using logic as:

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

Is that a efficient way because I want to do this operation continuously. Is there any other way which is faster than this way?

Why don'y you just use a List<string> and then add elements to it. The index of the element in the list will represent the Key. So:

List<string> myList = ...

and then:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM