Creating a dictionary key based on a loop position

I am going to a directory collecting some files and then adding them to the dictionary.

For the first time in the loop, the key must be A, the second time B, etc. Afer 26 / Z numbers represent different characters, and from 33 starts from lowercase to 49, which is a lowercase q.

Without a massive if statement, to say that if I == 1, then Key is "A", etc. etc., how can I keep this code in order?

+4
source share
4 answers

It looks like you just need to keep an index of where you have it, and then some display function:

int index = 0; foreach (...) { ... string key = MapIndexToKey(index); dictionary[key] = value; index++; } ... // Keys as per comments private static readonly List<string> Keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopq" .Select(x => x.ToString()) .ToList(); // This doesn't really need to be a separate method at the moment, but // it means it flexible for future expansion. private static string MapIndexToKey(int index) { return Keys[index]; } 

EDIT: I updated the MapIndexToKey method to simplify it. It is not clear why a string key is needed if you use only one character, though ...

Another edit: I believe you could just use:

 string key = ((char) (index + 'A')).ToString(); 

instead of having a matching function at all, considering your requirements, since the characters are adjacent in the Unicode order of "A" ...

+4
source

Continue increasing from 101 to 132, ignoring the missing sequence and converting them to a character. http://www.asciitable.com/

Use a reminder (divide by 132) to identify the second cycle

+1
source

This gives you the ability to match letters to specific numbers, possibly not sorted alphabetically.

  var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" .Select((chr, index) => new {character = chr, index = index + 1 }); foreach(var letter in letters) { int index = letter.index; char chr = letter.character; // do something } 
+1
source

What about:

 for(int i=0; i<26; ++i) { dict[(char)('A'+ (i % 26))] = GetValueFor(i); } 
0
source

All Articles