我正在努力学习C#。我想创建一个字典,其1,8,15 ......第167个键应该是JUPITER,2,9,16 ......所以应该是MARS等。是吗可能更简单的方法吗?感谢。
public enum Planets : int { JUPITER = 1, MARS, SUN, VENUS, MERCURY, MOON, SATURN }
Dictionary<int, string> Dict = new Dictionary<int, string>();
for (int key = 1; key < 169; key++)
{
if (key % 7 == 1)
{
Dict.Add(key, Planet.JUPITER.ToString());
}
else if (key % 7 == 2)
{
Dict.Add(key, Planet.MARS.ToString());
}
else if (key % 7 == 3)
{
Dict.Add(key, Planet.SUN.ToString());
}
else if (key % 7 == 4)
{
Dict.Add(key, Planet.VENUS.ToString());
}
else if (key % 7 == 5)
{
Dict.Add(key, Planet.MERCURY.ToString());
}
else if (key % 7 == 6)
{
Dict.Add(key, Planet.MOON.ToString());
}
else
{
Dict.Add(key, Planet.SATURN.ToString());
}
答案 0 :(得分:3)
如何在7
中按for
增加并使用Add
中的偏移:
for (int key = 1; key < 169; key += 7)
{
Dict.Add(key + 0, Planet.JUPITER.ToString());
Dict.Add(key + 1, Planet.MARS.ToString());
Dict.Add(key + 2, Planet.SUN.ToString());
Dict.Add(key + 3, Planet.VENUS.ToString());
Dict.Add(key + 4, Planet.MERCURY.ToString());
Dict.Add(key + 5, Planet.MOON.ToString());
Dict.Add(key + 6, Planet.SATURN.ToString());
}
或仅使用key++
并一直运行直到您满意为止:
int key = 1;
while ( key < 169 )
{
Dict.Add(key++, Planet.JUPITER.ToString());
Dict.Add(key++, Planet.MARS.ToString());
Dict.Add(key++, Planet.SUN.ToString());
Dict.Add(key++, Planet.VENUS.ToString());
Dict.Add(key++, Planet.MERCURY.ToString());
Dict.Add(key++, Planet.MOON.ToString());
Dict.Add(key++, Planet.SATURN.ToString());
}
旋转和平冥王星。