简体   繁体   中英

Usage of Dictionaries in C#

I'm an old, old programmer so I'm very used to abuse Arrays but I will need to start using dictionaries since they can dynamically expand and Arrays can't.

Now... I need to populate values for a solar system where each body in that solar system have perhaps about 20-30 different values.

My intention was to use a dictionary where each body has it's own unique Key and a value, such as...

Dictionary<int,string> BodyName = new Dictionary<int,string>()
Dictionary<int,int> BodySize = new Dictionary<int,int>()
Dictionary<int,int> BodyX = new Dictionary<int,int>()
Dictionary<int,int> BodyY = new Dictionary<int,int>()
Dictionary<int,int> BodyVelocity = new Dictionary<int,int>()

etc...

my question is what's the best way to go about to retrieve the values from all these dictionaries? The key for each 'body" is the same in each dictionary. I know I can do this with lots of loops, but that seems quite wasteful on CPU cycles and that is a bad thing for me.

I also considered Dictionary,List but that has other issues I don't particularly like.

Create a composite type, and use that.

Sticking with Dictionaries is suitable if the key is a unique identifier - a planet ID? a planet name? - that must be used to look up the data. Don't forget that iteration over dictionaries is non-deterministic.

Dictionary<int,PlanetaryBody> Bodies = new Dictionary<int,PlanetaryBody>()

On the other hand, a sequence is suitable if the planets are only iterated (or accessed by positional indices). In this case, using a List often works well.

List<PlanetaryBody> Bodies = new List<PlanetaryBody>();
// Unlike arrays, Lists grows automatically! :D
Bodies.Add(new PlanetaryBody { .. }); 

(I very seldom choose an array over a List - it's better sometimes, but not often.)


The composite type (ie class ) is used to group the different attributes into a larger concept or classification group:

class PlanetaryBody {
    public string Name { get; set; }
    public double Mass { get; set; }
    // etc.
}

Just use a class for that.

public class Planet {
   public int Id { get; set; }
   public string Name { get; set; }
   public int Size { get; set; }
  // and so on for each property of whatever type you need.
}

When you need a new Planet just new up:

var planet = new Planet();
planet.Name = "Saturn";
// again finish populating the properties.

To add it to a list:

var list = new List<Planet>();
list.Add(planet);
// adding the planet you created above.

Then look into manipulating lists and so on using LINQ

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