开发者

Making a Dictionary's key based on a for loop position

I am going to a directory picking up some files and then adding them to a Dictionary.

The first time in the loop the key needs to be A, second time B etc. Afer 26/Z the number represents different characters and from 33 it starts at lowercase a up to 49 which is lowercase q.

Without having a massive if statement to say if i ==开发者_高级运维 1 then Key is 'A' etc etc how can I can keep this code tidy?


Sounds like you just need to keep an index of where you've got to, then some mapping 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's flexible for future expansion.
private static string MapIndexToKey(int index)
{
    return Keys[index];
}

EDIT: I've updated the MapIndexToKey method to make it simpler. It's not clear why you want a string key if you only ever use a single character though...

Another edit: I believe you could actually just use:

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

instead of having the mapping function at all, given your requirements, as the characters are contiguous in Unicode order from 'A'...


Keep incrementing from 101 to 132, ignoring missing sequence, and convert them to character. http://www.asciitable.com/

Use reminder (divide by 132) to identify second loop


This gives you the opportunity to map letters to specific numbers, perhaps not alphabet ordered.

    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
     }


How about:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜