I'm trying to learn C#.I want to create a dictionary whose 1,8,15...167th key should be JUPITER, 2,9,16 .... so on should be MARS etc. Is it possible easier way to make it? Thanks.
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());
}
How about increment by 7
in the for
and using an offset in the 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());
}
or just using key++
and running until your satisfied:
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());
}
Revolve in Peace Pluto.
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.